gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:30 25 4
gpt4 key购买 nike

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

我认为异常信息没有用。

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

最佳答案

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

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

关于c# - HttpResponseHeaders .contains() 在 C# 中使用 HttpClient 抛出异常的可能原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32819711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com