c# - 使用 MultipartFormDataContent 生成错误的 Content-Type header

标签 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 header :

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);

... 但它没有用,错误消息是:“无法添加值,因为 header ‘Content-Type’不支持多个值。”和“值‘multipart/form-data,boundary=----CustomBoundary8d0f024297b32d5’的格式无效。”,相应地。

如何将正确的 Content-Type header 添加到请求中,以便边界值不包含在引号中?

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

最佳答案

通过从 MultipartFormDataContent 中删除标题并在不验证的情况下重新添加它来解决此问题:

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

关于c# - 使用 MultipartFormDataContent 生成错误的 Content-Type header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569770/

相关文章:

c# - 使用 ConfigureAwait(false) 和 Task.Run 有什么区别?

64-bit - .Net 内存转储中有大量死线程

sharepoint - 客户端对象模型将内容类型添加到列表

html - 为什么这个 SVG 可以在浏览器中以原始方式查看,但不能在网页中查看?

c# - 如何获取多维数组的宽和高?

c# - 在 wpf 应用程序中捕获 Windows 关闭事件

c# - 在 Metro 应用程序中实现 Logger 类

java - 如何使用 Grails 邮件插件设置内容类型?

c# - Facebook 风格的 ASP.NET 按钮

c# - WPF 处理转换器错误和 View 模型验证