Wrong Content-Type header generated using MultipartFormDataContent

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I have the following code:

private static string boundary = "----CustomBoundary" + DateTime.Now.Ticks.ToString("x");  private static async Task<string> PostTest() {     string servResp = "";      using (var content = new MultipartFormDataContent(boundary))     {         content.Add(new StringContent("105212"), "case-id");         content.Add(new StringContent("1/14/2014"), "dateFrom");         content.Add(new StringContent("1/15/2014"), "dateTo");          HttpClientHandler handler = new HttpClientHandler();         cookieContainer = new CookieContainer();         handler.CookieContainer = cookieContainer;          HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://somewebsite.com/form");         request.Headers.ExpectContinue = false;         request.Content = content;          httpClient = new HttpClient(handler);          HttpResponseMessage response = await httpClient.SendAsync(request);         response.EnsureSuccessStatusCode();          servResp = await response.Content.ReadAsStringAsync();     }      return servResp; } 

When I run it, I see the Content-Type header in Fiddler:

Content-Type: multipart/form-data; boundary="----CustomBoundary8d0f01e6b3b5daf" 

Because the boundary value is in quotes, the server ignores the request body. If I remove the quotes and run the request in Fiddler Composer, the request is being processed correctly.

I tried adding the content headers:

//request.Content.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary); //request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data; boundary=" + boundary); 

... but it didn't work, the error messages were: "Cannot add value because header 'Content-Type' does not support multiple values." and "The format of value 'multipart/form-data, boundary=----CustomBoundary8d0f024297b32d5' is invalid.", correspondingly.

How can I add the proper Content-Type header to the request so that the boundary value would not be enclosed in quotes?

Content-Type: multipart/form-data; boundary=----CustomBoundary8d0f01e6b3b5daf 

回答1:

Solved this by removing the header from MultipartFormDataContent and re-adding it back without validation:

content.Headers.Remove("Content-Type"); content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!