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
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);
As Darrel Miller pointed out in the RFC: ( which I find here ) https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.1
The quotes are not NORMALLY necessary. But MAY BE necessary if the boundary value has characters illegal in a header value. (E.g., colon, comma, space, ...)
ILLEGAL:
Content-Type: multipart/form-data, boundary=abc:def
LEGAL:
Content-Type: multipart/form-data, boundary="abc:def"
The multipart markers, with the lead and eventually trailing double hyphens, MUST NOT have the quotes:
ILLEGAL:
--"abc:def"
LEGAL:
--abc:def
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With