4

I know I can just typecast the result from GetHttpCode() to HttpStatusCode, but I don't like to typecast enums. Especially because the MSDN doc doesn't explicitely say that the values of the enums are always the exact corresponding http status code.

I feel that GetHttpCode() should just return HttpStatusCode.

Should I just stop complaining and typecast?

catch(HttpException ex)
{
    switch((HttpStatusCode)ex.GetHttpCode())
    {
        case HttpStatusCode.NotFound: 
            // Do stuff...
            break;
        // More cases...
    }
}

EDIT: note that HttpWebResponse.StatusCode is of type HttpStatusCode

5 Answers 5

9

It's worth noting that HTTP permits custom status codes, so it's not guaranteed that the enum will contain the value from your response. For this reason, it's sensible for the API to return the int value instead of trying to use the enum.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I wonder why HttpStatusCode is an enum then and not just a static class with constant ints. Here a guy defines his own to be able to support custom values (webdav?): devio.wordpress.com/2007/11/14/http-status-codes-in-c. HttpWebResponse.StatusCode is of type HttpStatusCode. I think it's confusing that it could contain undefined enum values.
An enum is useful in the majority of cases: within the boundaries of the .NET framework and the standard behaviour of Http, it's useful to have an Enum type to work with. That enum (according to MSDN) "contains the values of the status codes defined in RFC 2616 for HTTP 1.1." I imagine that it's far more likely to want to return a custom error value than a custom success value, and that's why only the custom exception type includes the integer field. Still, that seems a strange and slightly inconsistent choice!
1

HTTP status codes don't have to come from a fixed list, though they usually do. Using an enum is a convenience. Requiring an enum would be wrong.

2 Comments

See my comment to Dan's answer. HttpWebResponse.StatusCode is of type HttpStatusCode.
...and that's odd. Looking in Reflector, it looks like the underlying integer is merely cast to HttpStatusCode, which means that it could have a value that's not defined in the enum.
0

A response contains an integer value for the error code. The int is the actual error code. The enumeration allows for a 'friendly' representation of the error code.

Comments

0

Should I just stop complaining and typecast?

Yes. Or work with the corresponding integer values.

Comments

0

Yes, you should do it like that. Most of all, since the code you yourself provided shields you from working with any integer values or status numbers all together. So technically, it does not matter, whether the enum-values correspont to the status numbers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.