c# – 使用MultipartFormDataContent生成错误的Content-Type头文件

我有以下代码
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

解决方法

通过从MultipartFormDataContent中删除标题并重新添加它而不进行验证来解决此问题:
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type","multipart/form-data; boundary=" + boundary);

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...