How to get the status code using HttpClient in C#

By FoxLearn 1/21/2025 8:41:32 AM   29
When working with HttpClient in C#, it's important to handle the response status codes to ensure that your application behaves as expected.

The status code indicates whether the request was successful or if there was an error.

In this article, we'll explore different methods to get and handle the status code using HttpClient.

Using IsSuccessStatusCode

The IsSuccessStatusCode property of the HttpResponseMessage class is a quick way to determine if the request was successful. It returns true if the status code is within the range of 200-299, indicating a successful request. Otherwise, it returns false.

For example, How to use IsSuccessStatusCode:

var response = await httpClient.GetAsync(moviesUrl);

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

In this example, if the request fails, the error status code (e.g., 429) will be displayed in the console.

Using EnsureSuccessStatusCode() and HttpRequestException

Another way to handle status codes is by using EnsureSuccessStatusCode(). This method throws an HttpRequestException if the status code is outside the successful range (200-299).

For example, using EnsureSuccessStatusCode():

try
{
    var response = await httpClient.GetAsync(moviesUrl);
    response.EnsureSuccessStatusCode(); // Throws exception if status code indicates failure
}
catch (HttpRequestException httpEx)
{
    if (httpEx.StatusCode.HasValue)
    {
        // Request failed with an error status code
        Console.WriteLine($"Request failed. Error status code: {(int)httpEx.StatusCode}");
    }
    else
    {
        // Request failed due to an exception (connection failure, etc.)
        Console.WriteLine(httpEx.Message);
    }
}

If an error status code (e.g., 429) is returned, the following message will be displayed:

Request failed. Error status code: 429

Get the Status Code from HttpRequestException Before .NET 5

Before .NET 5, the HttpRequestException did not have a StatusCode property. If you're working with a version prior to .NET 5, you have two options for handling error status codes.

Use IsSuccessStatusCode and Throw a Custom Exception

Instead of relying on EnsureSuccessStatusCode(), you can manually check IsSuccessStatusCode and throw a custom exception that includes the status code.

First, create a custom exception class:

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

Then, use IsSuccessStatusCode to check the response and throw the custom exception:

var response = await httpClient.GetAsync(moviesUrl);

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

In the error handling code, you can catch the custom exception and retrieve the status code:

try
{
    var movieData = await GetMovieData();
}
catch (HttpRequestException httpEx)
{
    if (httpEx is HttpErrorStatusCodeException httpErrorStatusEx)
    {
        Console.WriteLine($"Request failed with status code: {httpErrorStatusEx.ErrorStatusCode}");
    }
    else
    {
        // Request failed due to an exception (connection failure, etc.)
        Console.WriteLine(httpEx.Message);
    }
}

Output:

Request failed with status code: NotFound

Parse the Status Code Out of the Exception Message

If you can't use .NET 5 and must rely on EnsureSuccessStatusCode(), you can parse the status code from the exception message. While this approach is not ideal and should be used as a last resort, it can be useful when no other options are available.

The exception message looks like this:

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

You can extract the status code from this message as follows:

using System.Net;

try
{
    var response = await httpClient.GetAsync(moviesUrl);
    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

In C#, handling status codes is essential for building robust applications that use HttpClient. By using IsSuccessStatusCode, EnsureSuccessStatusCode(), or custom exception handling, you can effectively manage the response and errors. If you’re using .NET versions before 5, custom exceptions or parsing the status code from the exception message are viable options.