【发布时间】:2020-03-11 07:38:56
【问题描述】:
从HttpClient 获取HttpResponseMessage 时,是否存在Content 可能为null 的情况?
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.stackoverflow.com/");
if (response.Content == null) {
// Can this happen?
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
// ...
}
如果您认为可以是null,请提供一个示例进行复现。
我尝试了很多东西,但无法获得null:
╔═══════════════════════╦═════════════════════════════════╦═══════════════════════╗
║ Request ║ Response ║ Content ║
╠═══════════════════════╬═════════════════════════════════╬═══════════════════════╣
║ GET http ║ 200 OK, a response ║ The response ║
║ GET http ║ 200 OK, empty response ║ Empty string ║
║ GET http ║ 204 No Response, empty response ║ Empty string ║
║ GET http ║ 400 Bad Request, a response ║ The response ║
║ GET http ║ 400 Bad Request, empty response ║ Empty string ║
║ GET http ║ 500 Bad Request, empty response ║ Empty string ║
║ HEAD http ║ 200 OK, empty response ║ Empty string ║
║ OPTIONS http ║ 200 OK, empty response ║ Empty string ║
║ GET http, bad DNS ║ (never hit) ║ HttpRequestException ║
║ GET http, bad scheme ║ (never hit) ║ ArgumentException ║
║ GET http ║ Never respond ║ TaskCanceledException ║
╚═══════════════════════╩═════════════════════════════════╩═══════════════════════╝
【问题讨论】:
-
根据规范,根据响应状态码,body中可能没有内容。一个例子是
204 No Contentstatus code。不过,不知道 C# 从中得到了什么。 -
HEAD也没有返回正文,但是来自 HttpClient 的内容返回一个空字符串而不是null。知道我们是否需要检查null或者我们是否总是可以期待一个空字符串会很有趣。 -
我刚刚用一个错误的方案和一个不存在的主机尝试了这个 - 在这些情况下,GetAsync 返回的任务是错误的。我想知道提供格式错误响应的服务器会发生什么...
-
您可以使用扩展方法来确保它是一个空字符串(即将
null转换为空字符串)。 -
@Namoshek 这可能是保持代码整洁的一个很好的解决方法。但如果它实际上是不必要的,我宁愿不这样做。所以,我想一劳永逸地弄清楚这一点。
标签: c# .net-core httpclient