132

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);
4
  • you need to do int code = (int)Response.StatusCode from there you will need to create your own Enum check here for working example stackoverflow.com/questions/1330856/…
    – MethodMan
    Sep 14, 2015 at 16:52
  • Are you by any chance using the HttpClient class?
    – dcastro
    Sep 14, 2015 at 16:56
  • 1
    @dcastro No, I'm sorry. I'm using a high-level API that may (or may not) use it internally. The API exposes the response's status code, but does not expose the inner HttpResponseMessage for example Sep 14, 2015 at 16:57
  • 1
    @MatiCicero That's too bad :/ You can always reuse the implementation of HttpResponseMessage.IsSuccessStatusCode (see my answer) which is exactly the same as your first approach, and make it an extension method on the HttpStatusCode type.
    – dcastro
    Sep 14, 2015 at 17:04

7 Answers 7

245

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.

2
  • 3
    FYI: Was 'response.IsSuccessful' for me. Feb 15, 2019 at 15:14
  • Your answer is quite helpful but now it works like: if (response.IsCompletedSuccessfully) { // }
    – Saima
    Jun 19, 2019 at 13:07
21

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.

3
  • 1
    This worked perfectly for me as I only had a HttpStatusCode and not a Response message. Good job!
    – Todd Vance
    Jun 28, 2017 at 21:17
  • 11
    "The accepted answer bothers me a bit as it contains magic numbers, (although they are in standard)" - They're not "magic" if they're standardized, well understood, and never going to change. There is absolutely nothing wrong with using the codes directly. If you have IsSuccessStatusCode then great, use it (as the accepted answer says to.) Otherwise, don't add your own cruft by using an abstraction unless you're performing this check all over the place
    – Ed S.
    Jan 8, 2018 at 18:14
  • 7
    Have in mind that instantiating HttpResponseMessage to use one of its properties takes more time than checking two logical conditions with int.
    – Miro J.
    Apr 27, 2020 at 21:43
18

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().

3
  • Extension methods are cool, but I'm confused - doesn't this do the same thing as the HTTPResponseMessage's IsSuccessStatusCode property that's used with the HTTPClient or the IHTTPClientFactory? @DCastro even shows us that it's implemented exactly like this in .NET. When/why would I use an extension method like this for HTTP Status Codes in the 2xx range? Oct 18, 2019 at 15:53
  • 5
    @sfors, yes, but what if you only have an HttpStatusCode in scope? There are plenty of libraries that don't use or surface HttpResponseMessage but do give you the status code.
    – bojingo
    Oct 29, 2019 at 12:47
  • @bojingo I still don't see the need for an extension method: if the library only returns the status code (say, 404), do httpResponse = new HttpResponseMessage((HttpStatusCode)404); and move on.
    – Sam
    Nov 6 at 15:49
13

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); }
}
12

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);
}
4

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.

2

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.