文档上传 API 通过 Postman 工作,但不能通过我的 .NET 代码工作。知道问题出在哪里吗?

问题描述 投票:0回答:1

我正在尝试通过 .NET WebApi 将文档上传到服务。该服务接受包含两部分的多部分/表单数据请求。第一部分是json,第二部分是文件。 该 API 通过 Postman 工作。我将 Postman 生成的 C# HttpClient 代码复制到我的应用程序中,但它失败并出现 500 错误。 我正在尝试使用与通过 Postman 相同的文件和相同的 json 数据。

这是我的代码的副本:

string url = "Some url";//leaving out the actual url here
string token = GetToken();//invoke separate method to get an Oauth2 token - confirmed that this is working
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;//tried with and without this line
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, serviceUrl);
client.Timeout = TimeSpan.FromSeconds(30);
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Host = "destinationurl.com";//leaving out the actual url here.
var content = new MultiPartFormDataContent();
content.Add(new StringContent(JsonSerializer.Serialize(my_object), Encoding.UTF8, "application/json"), "keywords");
var streamContent = new StreamContent(File.OpenRead(path_to_file));
streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
content.Add(streamContent, "proposalFile", path);
request.Content = content;
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();

您知道这里可能存在什么问题吗?或者我可以尝试调用此服务的任何其他方式?任何建议将不胜感激。

编辑: 我正在调用的服务在内部调用另一个服务。我收到的消息是“内部服务上的帖子失败 500”。有一两次我还收到一条异常消息“消费流时出现异常”。

c# dotnet-httpclient
1个回答
0
投票

事实证明,问题出在文件名上——我必须传递一个不包含空格的文件名。然后就成功了。

© www.soinside.com 2019 - 2024. All rights reserved.