Checking if HttpStatusCode represents success or failure

If you’re using the HttpClient class, then you’ll get a HttpResponseMessage back.

This class has a useful property called IsSuccessStatusCode that will do the check for you.

using (var client = new HttpClient())
{
    var response = await client.PostAsync(uri, content);
    if (response.IsSuccessStatusCode)
    {
        //...
    }
}

In case you’re curious, this property is implemented as:

public bool IsSuccessStatusCode
{
    get { return ((int)statusCode >= 200) && ((int)statusCode <= 299); }
}

So you can just reuse this algorithm if you’re not using HttpClient directly.

You can also use EnsureSuccessStatusCode to throw an exception in case the response was not successful.

Leave a Comment