Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can HttpClient's reponse Content be null?

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 ║
╚═══════════════════════╩═════════════════════════════════╩═══════════════════════╝
like image 580
Anders Carstensen Avatar asked Sep 15 '25 14:09

Anders Carstensen


1 Answers

So as MSDN says, yes it can be null, but you should use EnsureSuccessStatusCode to check response valid or not

like image 179
Maks Shapovalov Avatar answered Sep 18 '25 05:09

Maks Shapovalov