【问题标题】:Can HttpClient's reponse Content be null?HttpClient 响应内容可以为空吗?
【发布时间】: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 Content status code。不过,不知道 C# 从中得到了什么。
  • HEAD 也没有返回正文,但是来自 HttpClient 的内容返回一个空字符串而不是 null。知道我们是否需要检查 null 或者我们是否总是可以期待一个空字符串会很有趣。
  • 我刚刚用一个错误的方案和一个不存在的主机尝试了这个 - 在这些情况下,GetAsync 返回的任务是错误的。我想知道提供格式错误响应的服务器会发生什么...
  • 您可以使用扩展方法来确保它是一个空字符串(即将null 转换为空字符串)。
  • @Namoshek 这可能是保持代码整洁的一个很好的解决方法。但如果它实际上是不必要的,我宁愿不这样做。所以,我想一劳永逸地弄清楚这一点。

标签: c# .net-core httpclient


【解决方案1】:

所以MSDN says,是的,它可以为空,但你应该使用EnsureSuccessStatusCode来检查响应是否有效

【讨论】:

  • 这是一个很好的观察。但是,由于您所指的句子以“在 .NET Framework 和 .NET Core 2.2 及更早版本中”为前缀,因此仍不完全清楚。 .NET Core 3.1 中还可以是null 吗?再说一次,究竟在哪些情况下可以是null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2013-09-14
  • 2021-04-08
相关资源
最近更新 更多