问题是关于 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 header name。确保请求标头与 HttpRequestMessage 一起使用,响应标头与 HttpResponseMessage 一起使用,内容标头与 HttpContent 对象一起使用。
我认为异常信息是缺乏使用。
你能告诉我'headers.Contains(“Content-Length”)'抛出异常的可能原因吗?