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



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

            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") '时,它抛出一个系统。异常:错误的标头名称。确保请求头与HttpRequestMessage一起使用,响应头与HttpResponseMessage一起使用,内容头与HttpContent对象一起使用。

我认为异常信息是没有用的。

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

您可以像这样检查标题是否存在

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

最新更新