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

时间:2015-09-28 09:30:59

标签: c# .net httpclient response-headers

问题是关于在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:未使用的标头名称。确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用。

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

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

1 个答案:

答案 0 :(得分:0)

你可以检查这样的标题存在

{{1}}