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);
The 200 OK status code means that the request was successful, but the meaning of success depends on the request method used: GET: The requested resource has been fetched and transmitted to the message body. HEAD: The header fields from the requested resource are sent in without the message body.
OK indicates that the request succeeded and that the requested information is in the response. This is the most common status code to receive.
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With