c# - HttpClient 响应内容可以为空吗?

标签 c# .net-core httpclient

当收到 HttpResponseMessage来自 HttpClient , 是否有任何情况下其 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 ║
╚═══════════════════════╩═════════════════════════════════╩═══════════════════════╝

最佳答案

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

关于c# - HttpClient 响应内容可以为空吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631212/

相关文章:

c# - 为什么在 Visual Studio 2010 中保存 xml 文件非常慢?

c# - 如何使用使用 Microsoft 增强型 RSA 和 AES 加密提供程序的证书请求创建自签名证书

c# - 内联变量声明不编译

java - Android 1.6 中 bundle 了哪个版本的 Apache HTTP 客户端?

android - 检测并处理需要登录wifi

rest - 英特尔伽利略 Azure REST 调用

c# - 设置特定 Pivot Item 的内容

c# - 有没有办法在编译时根据对象的状态限制对象的可用方法?

c# - 检查文件是否正在使用

unit-testing - dotnet 测试 Coverlet 错误覆盖