如何通过API将文档上传到watson发现服务。 ASP.net

时间:2017-12-18 12:42:14

标签: c# asp.net-mvc ibm-watson watson-discovery

我使用以下API将文件上传到watson发现服务。即使我提供了有效的类型,我也会将响应视为不受支持的文件格式。 API:discovery service api

 public async Task<ActionResult> Index()
    {
        using (var httpClient = new HttpClient())
        {

            //ADD BASIC AUTH
            var authByteArray = Encoding.ASCII.GetBytes("{auth key}");
            var authString = Convert.ToBase64String(authByteArray);
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString);

            var text = string.Empty;
            var uri = "https://gateway.watsonplatform.net/discovery/api/v1/environments/{envid}/collections/{collectionid}/documents?version=2017-11-07";


            var content = new MultipartFormDataContent();
            var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Views/UploadDocument/civilwar-api1.html"));
            var file = new StreamContent(new MemoryStream(bytes));
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/html");
            content.Add(new StreamContent(new MemoryStream(bytes)), "file");

            var response = await httpClient.PostAsync(uri, content);
            var text1 = await response.Content.ReadAsStringAsync();

        }

        return View();
    }

api回复为:{ "code" : 415, "error" : "Unsupported Media Type" }

2 个答案:

答案 0 :(得分:1)

正如您在Watson Developer Cloud中所看到的,您可以使用.NET SDK

在此存储库中,您可以看到examples使用Watson中的每项服务。

添加文档的方法:

#region Documents
        private void AddDocument()
        {
            Console.WriteLine(string.Format("\nCalling AddDocument()..."));
            using (FileStream fs = File.OpenRead(_filepathToIngest))
            {
                var result = _discovery.AddDocument(_createdEnvironmentId, _createdCollectionId, _createdConfigurationId, fs as Stream, _metadata);

                if (result != null)
                {
                    Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
                    _createdDocumentId = result.DocumentId;
                }
                else
                {
                    Console.WriteLine("result is null.");
                }
            }
        }

答案 1 :(得分:0)

尝试httpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header