我有如下代码:
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;
}
当我运行它时,在Fiddler中我看到了Content-Type头:
Content-Type: multipart/form-data; boundary="----CustomBoundary8d0f01e6b3b5daf"
由于边界值被引号括起来,服务器会忽略请求体。如果我移除引号并在Fiddler Composer中运行请求,则请求将被正确处理。
我尝试添加内容标头:
//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);
...但是它没有生效,出现了错误信息:“无法添加值,因为标题“Content-Type”不支持多个值。”和“值'multipart/form-data,boundary=----CustomBoundary8d0f024297b32d5'的格式无效。”,相应地。
我该如何添加适当的Content-Type头到请求中,以便边界值不会被引号括起来?
Content-Type: multipart/form-data; boundary=----CustomBoundary8d0f01e6b3b5daf