C# – Checking if HttpStatusCode represents success or failure

.net, c++, system.net

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

Best Solution

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.