131

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);
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • you need to do `int code = (int)Response.StatusCode` from there you will need to create your own `Enum` check here for working example http://stackoverflow.com/questions/1330856/getting-http-status-code-number-200-301-404-etc-from-httpwebrequest-and-ht – MethodMan Sep 14 '15 at 16:52
  • Are you by any chance using the `HttpClient` class? – dcastro Sep 14 '15 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 – Matias Cicero Sep 14 '15 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 '15 at 17:04

7 Answers7

239

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.

dcastro
  • 66,540
  • 21
  • 145
  • 155
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.

user232548
  • 435
  • 4
  • 11
  • This worked perfectly for me as I only had a HttpStatusCode and not a Response message. Good job! – Todd Vance Jun 28 '17 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 08 '18 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 '20 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().

bojingo
  • 572
  • 1
  • 6
  • 12
  • 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? – sfors says reinstate Monica Oct 18 '19 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 '19 at 12:47
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); }
}
TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
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);
}
ozba
  • 6,522
  • 4
  • 33
  • 40
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.

usr
  • 168,620
  • 35
  • 240
  • 369
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);
}
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74