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

发布于 2022-09-01 19:10:43 字数 7223 浏览 27 评论 0

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

clipboard.png
红色标记部分抛出异常:

clipboard.png

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文