Kugel Kugel - 2 months ago 26x
C# Question

How do I get StatusCode from HttpRequestException?

I'm probably missing something obvious here.

I'm using HttpClient which throws HttpRequestException that contains StatusCode in the Message string.

How can I access that StatusCode?

Edit: More info, I wrote this question in rush.

I'm using HttpClient to access another API within my WebApi project. Yes, I know why I'm calling

. I want to propagate some errors downstream such as 404 403.

All I wanted was to consistently transform
using custom

Unfortunately, HttpRequestException does not carry any extra info I could use besides the message. I was hoping to uncover StatusCode in raw (int or enum) form.

Looks like I can either:

  1. Use the message to switch the status code (bleh)

  2. Or create my version of EnsureSuccessStatusCode and throw exception that's actually usable.


Status code was passed as part of a string to HttpRequestException so that you cannot recover it from such exceptions alone.

The design of System.Net.Http requires you to access HttpResponseMessage.StatusCode instead of waiting for the exception.


If you are now following the Microsoft guide, make sure you understand clearly why it asks you to call HttpResponseMessage.EnsureSucessStatusCode. If you don't call that function, there should be no exception.