当收到 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/