Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HttpClient.PostAsync not throw on failure?

Tags:

c#

asp.net

In an ASP.Net Core web service if an HttpClient.GetStringAsync call fails for 404 error or whatever, it throws an HttpRequestException. This is great.

If on the other hand an HttpClient.PostAsync call fails for 404, it does not throw an exception. I have to check the status code, fabricate an exception and throw it manually.

Why the discrepency, and is there a more elegant way of dealing with this?

HttpResponseMessage response = await _http.PostAsync("api/pollapi/request", new StringContent(requestInput));

if (!response.IsSuccessStatusCode)
{
   throw new HttpRequestException($"Response status does not indicate success: {(int)response.StatusCode} ({response.StatusCode}).");
}
like image 597
Neutrino Avatar asked Jan 10 '18 10:01

Neutrino


1 Answers

You can use HttpResponseMessage.EnsureSuccessStatusCode method that:

Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.

like image 164
Yurii Avatar answered Oct 04 '22 17:10

Yurii