I am trying to upload a document to a service through a .NET WebApi. The service takes a multipart/form-data request with two parts. The first part is json, the second part is a file. The api is working through Postman. I copied the Postman-generated C# HttpClient code into my application, and it is failing from there with a 500 error. I am trying with the same file and same json data as through Postman.
Here is a copy of my code:
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();
Do you know what could be the issue here? Or any alternative ways that I can try calling this service? Any advice would be greatly appreciated.
Edit: The service that I am calling calls another service internally. The message that I am getting is that "post on the internal service failed 500". Once or twice I also got an exception message "Exception while consuming stream".
It turned out that the problem was the fileName - I had to pass a fileName that didn't contain spaces. It then worked.