HttpWebRequest, HttpWebResponse, and the WebException

Standard

Calling the GetResponse() method on the HttpWebRequest class yields some interesting results. It determines that a status code of anything else but 200 (OK) is an exceptional case and throws a WebException exception.

The following code demonstrates how to return the status code even if the URL in the request is not OK.

HttpStatusCode httpStatusCode;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://invalidsitename.net/");
try
{
    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        httpStatusCode = httpWebResponse.StatusCode; //OK
    }
}
catch (WebException webException)
{
    if (webException.Response != null)
    {
        HttpWebResponse httpWebExceptionResponse = (HttpWebResponse)webException.Response;
        httpStatusCode = httpWebExceptionResponse.StatusCode; //Something other than OK
    }
    else
    {
        throw webException; //Invalid host name
    }
}
return httpStatusCode;