在 System.Net.Http.Headers.HttpHeaders.Contains(String name)处抛出异常

在 System.Net.Http.Headers.HttpHeaders.CheckHeaderName(String name) 在 System.Net.Http.Headers.HttpHeaders.Contains(String name)处抛出异常

具体情况如下:

 public static HttpClientResult httpPost(string url, IDictionary<string, string> headMap, IDictionary<string, string> @params, string filePath, ProgressNotifier progressNotifier)
        {
            string response = "";
            string startTime = DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz", new CultureInfo("en-US")); //请求时间
            string endTime = "-";
            string statusCode = "-";
            string contentLength = "-";
            string contentType = "-";

            try
            {
                HttpClient hc = new HttpClient();
                hc.Timeout = new TimeSpan(1000000000);
                HttpResponseMessage responseM = null;

                //设置request header
                if (headMap != null && headMap.Count > 0)
                {
                    foreach (string name in headMap.Keys)
                    {
                        hc.DefaultRequestHeaders.TryAddWithoutValidation(name, headMap[name]);
                    }
                }

                //设置request body体
                var paramsList = new List<KeyValuePair<string, string>>();

                if (filePath != null)
                {
                    //MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();    
                    //Discard
                    //BandwithLimiterFileBody fileBody = new BandwithLimiterFileBody(file, null, "application/octet-stream", null, BaseBlockUtil.maxRate, progressNotifier);
                    //mEntityBuilder.addPart("file", fileBody);
                    //mEntityBuilder.addTextBody("desc", file.Name);

                    var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
                    string fileName = Path.GetFileName(filePath);
                    var stringContent = new StringContent(fileName, Encoding.UTF8);
                    var content = new MultipartFormDataContent();
                    content.Add(fileContent, "file", fileName);
                    content.Add(stringContent, "desc");


                    if (@params != null && @params.Count > 0)
                    {
                        foreach (string name in @params.Keys)
                        {
                            //mEntityBuilder.addTextBody(name, @params[name], ContentType.create("text/plain", Charset.forName("UTF-8")));
                            //TODO 怎样设置MIME类型
                            content.Add(new StringContent(@params[name], Encoding.UTF8), name);
                        }
                    }

                    responseM = hc.PostAsync(new Uri(url), content).Result;
                }
                else if (@params != null && @params.Count > 0)
                {
                    foreach (string name in @params.Keys)
                    {
                        paramsList.Add(new KeyValuePair<string, string>(name, @params[name]));
                    }
                    //TODO 怎么在这里设置字符集    HttpEntity he = new UrlEncodedFormEntity(paramsList, "utf-8");
                    var content = new FormUrlEncodedContent(paramsList);
                    responseM = hc.PostAsync(new Uri(url), content).Result;
                }

                endTime = DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz", new CultureInfo("en-US"));

                //获取response headers 信息
                HttpResponseHeaders headers = responseM.Headers;
                IEnumerable<string> values;
                if (headers.Contains("Content-Length"))
                {
                    values = headers.GetValues("Content - Length");
                    IEnumerator i = values.GetEnumerator();
                    if (i.MoveNext())
                    {
                        contentLength = i.Current.ToString();
                    }
                }
                //TODO to check
                if (headers.Contains("Content-Type"))
                {
                    values = headers.GetValues("Content-Type");
                    IEnumerator i = values.GetEnumerator();
                    if (i.MoveNext())
                    {
                        // ReSharper disable once RedundantAssignment
                        contentType = i.Current.ToString();
                    }
                }

                //取得 http response body(content)
                int status;
                response = GetResponse(out status, responseM);

                if (status == 200)
                {
                    if (!(new JsonValidator()).validate(response))
                    {
                        response = EncodeUtils.urlsafeDecodeString(response);
                    }
                }
                return new HttpClientResult(status, response);
            }
            catch (Exception e)
            {
                statusCode = "500";
                endTime = DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz", new CultureInfo("en-US"));
                throw new Exception(e.ToString());
            }
            finally
            {
                //writeHttpLog(startTime, url, "-", (null != @params ? @params["token"] : "-"), (null != file ? file.Name : "-"), "-", "-", endTime, statusCode, contentType, contentLength, response);
            }
        }


红色标记部分抛出异常:

System.Exception: System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

   在 System.Net.Http.Headers.HttpHeaders.CheckHeaderName(String name)

   在 System.Net.Http.Headers.HttpHeaders.Contains(String name)

   在 com.chinanetcenter.api.util.HttpClientUtil.httpPost(String url, IDictionary`2 headMap, IDictionary`2 params, String filePath, ProgressNotifier progressNotifier) 位置 c:\Codes\SVN\wcs-sharp-sdk\wcs-csharp-sdk\main\util\HttpClientUtil.cs:行号 127
    在 com.chinanetcenter.api.util.HttpClientUtil.httpPost(String url, IDictionary`2 headMap, IDictionary`2 params, String filePath, ProgressNotifier progressNotifier) 位置 HttpClientUtil.cs: line 155
   在 com.chinanetcenter.api.util.HttpClientUtil.httpPost(String url, IDictionary`2 headMap, IDictionary`2 params, String filepath) 位置 HttpClientUtil.cs: line 35
   在 com.chinanetcenter.api.wsbox.FileUploadCommand.upload(String bucketName, String fileKey, String SrcFile, PutPolicy putPolicy, ProgressListener progressListener) 位置 FileUploadCommand.cs: line 164
   在 com.chinanetcenter.api.wsbox.FileUploadCommand.upload(String bucketName, String fileKey, String srcFile, PutPolicy putPolicy) 位置 FileUploadCommand.cs: line 207
   在 UnitTest.FileUploadCommandTest.uploadTest2() 位置 FileUploadCommandTest.cs: line 152
查看回复