首页 文章

HttpResponseHeaders .contains()使用HttpClient在C#中抛出异常的可能原因是什么?

提问于
浏览
2

问题是关于在C#中使用'HttpClient' . 当我从服务器端响应时,我遇到了以下问题 . 我使用'hc.DefaultRequestHeaders.TryAddWithoutValidation(name,headMap [name])'

HttpClient hc = new HttpClient();
            hc.Timeout = new TimeSpan(1000000000);
            HttpContent content = new StringContent(body, Encoding.UTF8);

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

            HttpResponseMessage responseM = hc.PostAsync(new Uri(url), content).Result;
            endTime = DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz", new CultureInfo("en-US"));

            HttpResponseHeaders headers = responseM.Headers;
            IEnumerable<string> values;
            if (headers.Contains("Content-Length"))
            {
               ...
            }

当我将代码测试为'headers.Contains(“Content-Length”)'时,它会抛出一个System.Exception:Misused Headers 名称 . 确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用 .

我认为异常信息缺乏使用 .

你能否告诉我抛出'headers.Contains(“Content-Length”)'的异常的可能原因?

1 回答

  • 0

    你可以检查这样的 Headers 存在

    if(Request.Headers["Content-Length"] != null)
    

相关问题