gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:26:07 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com