首页 > 解决方案 > HttpClient的响应内容可以为空吗?

问题描述

当得到一个HttpResponseMessagefromHttpClient时,有没有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 ║
╚═══════════════════════╩═════════════════════════════════╩═══════════════════════╝

标签: c#.net-corehttpclient

解决方案


正如MSDN 所说,是的,它可以为空,但您应该使用它EnsureSuccessStatusCode来检查响应是否有效


推荐阅读