Checking if HttpStatusCode represents success or failure
Solution 1
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
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
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 4
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 5
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);
}
Related videos on Youtube
Matias Cicero
Software Development Engineer @ Amazon Web Services
Updated on June 20, 2020Comments
-
Matias Cicero almost 4 years
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);
-
MethodMan over 8 yearsyou need to do
int code = (int)Response.StatusCode
from there you will need to create your ownEnum
check here for working example stackoverflow.com/questions/1330856/… -
dcastro over 8 yearsAre you by any chance using the
HttpClient
class? -
Matias Cicero over 8 years@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 -
dcastro over 8 years@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 theHttpStatusCode
type.
-
-
Todd Vance almost 7 yearsThis worked perfectly for me as I only had a HttpStatusCode and not a Response message. Good job!
-
Ed S. over 6 years"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 -
Topher Birth about 5 yearsFYI: Was 'response.IsSuccessful' for me.
-
Saima almost 5 yearsYour answer is quite helpful but now it works like: if (response.IsCompletedSuccessfully) { // }
-
sfors says reinstate Monica over 4 yearsExtension 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?
-
bojingo over 4 years@sfors, yes, but what if you only have an
HttpStatusCode
in scope? There are plenty of libraries that don't use or surfaceHttpResponseMessage
but do give you the status code. -
Miro J. about 4 yearsHave in mind that instantiating
HttpResponseMessage
to use one of its properties takes more time than checking two logical conditions withint
.