When getting a HttpResponseMessage
from HttpClient
, are there any cases where its Content
may be 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();
// ...
}
If you think it can be null
, please provide an example to reproduce it.
I have tried many things, but without being able to get 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 ║
╚═══════════════════════╩═════════════════════════════════╩═══════════════════════╝
So as MSDN says, yes it can be null, but you should use EnsureSuccessStatusCode
to check response valid or not
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With