Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HttpException.GetHttpCode() return an int instead of a System.Net.HttpStatusCode?

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

like image 875
Matthijs Wessels Avatar asked Dec 27 '22 16:12

Matthijs Wessels


2 Answers

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.

like image 139
Dan Puzey Avatar answered Feb 09 '23 02:02

Dan Puzey


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.

like image 38
Roger Lipscombe Avatar answered Feb 09 '23 02:02

Roger Lipscombe