Checking if HttpStatusCode represents success or failure

C#.Netsystem.net

C# Problem Overview


Let's suppose I have the following variable:

System.Net.HttpStatusCode status = System.Net.HttpStatusCode.OK;

How can I check if this is a success status code or a failure one?

For instance, I can do the following:

int code = (int)status;
if(code >= 200 && code < 300) {
    //Success
}

I can also have some kind of white list:

HttpStatusCode[] successStatus = new HttpStatusCode[] {
     HttpStatusCode.OK,
     HttpStatusCode.Created,
     HttpStatusCode.Accepted,
     HttpStatusCode.NonAuthoritativeInformation,
     HttpStatusCode.NoContent,
     HttpStatusCode.ResetContent,
     HttpStatusCode.PartialContent
};
if(successStatus.Contains(status)) //LINQ
{
    //Success
}

None of these alternatives convinces me, and I was hoping for a .NET class or method that can do this work for me, such as:

bool isSuccess = HttpUtilities.IsSuccess(status);

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

The accepted answer bothers me a bit as it contains magic numbers, (although they are in standard) in its second part. And first part is not generic to plain integer status codes, although it is close to my answer.

You could achieve exactly the same result by instantiating HttpResponseMessage with your status code and checking for success. It does throw an argument exception if the value is smaller than zero or greater than 999.

if (new HttpResponseMessage((HttpStatusCode)statusCode).IsSuccessStatusCode)
{
    // ...
}

This is not exactly concise, but you could make it an extension.

Solution 3 - C#

The HttpResponseMessage class has a IsSuccessStatusCode property, looking at the source code it is like this so as usr has already suggested 200-299 is probably the best you can do.

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

Solution 4 - C#

Adding to @TomDoesCode answer If you are using HttpWebResponse you can add this extension method:

public static bool IsSuccessStatusCode(this HttpWebResponse httpWebResponse)
{
    return ((int)httpWebResponse.StatusCode >= 200) && ((int)httpWebResponse.StatusCode <= 299);
}

Solution 5 - C#

I am partial to the discoverability of extension methods.

public static class HttpStatusCodeExtensions
{
    public static bool IsSuccessStatusCode(this HttpStatusCode statusCode)
    {
        var asInt = (int)statusCode;
        return asInt >= 200 && asInt <= 299;
    }
}

As long as your namespace is in scope, usage would be statusCode.IsSuccessStatusCode().

Solution 6 - C#

It depends on what HTTP resource you are calling. Usually, the 2xx range is defined as the range of success status codes. That's clearly a convention that not every HTTP server will adhere to.

For example, submitting a form on a website will often return a 302 redirect.

If you want to devise a general method then the code >= 200 && code < 300 idea is probably your best shot.

If you are calling your own server then you probably should make sure that you standardize on 200.

Solution 7 - C#

This is an extension of the previous answer, that avoids the creation and subsequent garbage collection of a new object for each invocation.

public static class StatusCodeExtensions
{
    private static readonly ConcurrentDictionary<HttpStatusCode, bool> IsSuccessStatusCode = new ConcurrentDictionary<HttpStatusCode, bool>();
    public static bool IsSuccess(this HttpStatusCode statusCode) => IsSuccessStatusCode.GetOrAdd(statusCode, c => new HttpResponseMessage(c).IsSuccessStatusCode);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatias CiceroView Question on Stackoverflow
Solution 1 - C#dcastroView Answer on Stackoverflow
Solution 2 - C#user232548View Answer on Stackoverflow
Solution 3 - C#TomDoesCodeView Answer on Stackoverflow
Solution 4 - C#ozbaView Answer on Stackoverflow
Solution 5 - C#bojingoView Answer on Stackoverflow
Solution 6 - C#usrView Answer on Stackoverflow
Solution 7 - C#Rob LyndonView Answer on Stackoverflow