使用MultipartFormDataContent生成错误的Content-Type标头

时间:2014-02-05 06:04:00

标签: c# .net-4.5 content-type multipartform-data dotnet-httpclient

我有以下代码:

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

2 个答案:

答案 0 :(得分:27)

通过从MultipartFormDataContent中删除标头并重新添加它而不进行验证来解决此问题:

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

答案 1 :(得分:0)

正如 Darrel Miller 在 RFC 中指出的那样: (我在这里找到) https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.1

引号通常不是必需的。但如果边界值在标头值中包含非法字符,则可能是必要的。 (例如,冒号、逗号、空格等)

非法:

Content-Type: multipart/form-data, boundary=abc:def

法律:

Content-Type: multipart/form-data, boundary="abc:def"

多部分标记,带前导和最后的双连字符,不能有引号:

非法:

--"abc:def"

法律:

--abc:def