How to Get Status Codes with HttpClient in C#

By FoxLearn 3/6/2025 9:27:34 AM   28
When using HttpClient to send requests, you can easily access the status code from the HttpResponseMessage object.

For example:

var response = await httpClient.GetAsync(apiUrl);

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
    // Handle not found scenario
}

Understanding Status Codes

Checking the status code is crucial to determine the outcome of the request and respond to any error codes (typically by throwing an exception). The HttpResponseMessage class provides two helpful methods for these tasks:

  • IsSuccessStatusCode: Returns true if the status code falls within the 200-299 range, indicating success.
  • EnsureSuccessStatusCode(): Throws an HttpRequestException if the request fails.

In this article, I’ll provide examples of how to utilize these methods.

Using IsSuccessStatusCode

The IsSuccessStatusCode property returns true if the response code is successful (200-299).

var response = await httpClient.GetAsync(apiUrl);

if (response.IsSuccessStatusCode)
{
    // Successful path
}
else
{
    // Error handling
    Console.WriteLine($"Request failed. Error status code: {(int)response.StatusCode}");
}

When an error status code is returned, the output will be:

Request failed. Error status code: 404

Using EnsureSuccessStatusCode() and HttpRequestException

If HttpClient receives an error status code (anything outside the 200-299 range), the EnsureSuccessStatusCode() method will throw an exception. This simplifies error handling since you only need to catch one type of exception.

Note: A different exception (TaskCanceledException) is thrown for timeouts.

For example, Using EnsureSuccessStatusCode() with HttpRequestException:

try
{
    var response = await httpClient.GetAsync(apiUrl);
    response.EnsureSuccessStatusCode();

    // Successful path
}
catch (HttpRequestException httpEx)
{
    Console.WriteLine($"Request failed. Error status code: {(int)httpEx.StatusCode}");
}

When an error occurs, the output will be:

Request failed. Error status code: 404

Retrieving the Status Code from HttpRequestException (Pre-.NET 5)

In .NET 5, Microsoft added the StatusCode property to HttpRequestException.

For versions prior to this, there are two options:

Option 1: Use IsSuccessStatusCode and Create a Custom Exception

You can use IsSuccessStatusCode instead of EnsureSuccessStatusCode() to control the thrown exception. Define a custom exception class with an HttpStatusCode property:

public class HttpErrorStatusCodeException : HttpRequestException
{
    public HttpErrorStatusCodeException(HttpStatusCode statusCode)
    {
        ErrorStatusCode = statusCode;
    }
    public HttpStatusCode ErrorStatusCode { get; }
}

Now, check IsSuccessStatusCode and throw this custom exception:

var response = await httpClient.GetAsync(apiUrl);

if (!response.IsSuccessStatusCode)
{
    throw new HttpErrorStatusCodeException(response.StatusCode);
}

The error handling can then retrieve the status code:

try
{
    var data = await FetchData();
}
catch (HttpRequestException httpEx)
{
    if (httpEx is HttpErrorStatusCodeException httpError)
    {
        Console.WriteLine($"Request failed with status code: {httpError.ErrorStatusCode}");
    }
}

Output:

Request failed with status code: NotFound

Option 2: Parse the Status Code from the Exception Message

When EnsureSuccessStatusCode() throws an exception, the message often contains the status code:

Response status code does not indicate success: 404 (Not Found).

You can parse this message to retrieve the status code:

try
{
    var response = await httpClient.GetAsync(apiUrl);
    response.EnsureSuccessStatusCode();
}
catch (HttpRequestException httpEx)
{
    var errorStatusCodeStart = "Response status code does not indicate success: ";

    if (httpEx.Message.StartsWith(errorStatusCodeStart))
    {
        var statusCodeString = httpEx.Message.Substring(errorStatusCodeStart.Length, 3);
        var statusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), statusCodeString);
        Console.WriteLine($"Error status code: {(int)statusCode} {statusCode}");
    }
}

Output:

Error status code: 404 NotFound

This serves as a proof of concept demonstrating a method to extract the status code when no other alternatives are available. Note that this code lacks error handling and does not account for localized exception messages.