Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Viewed 356755

I am trying to get the HTTP status code number from the HttpWebResponse object returned from a HttpWebRequest. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks.

HttpWebRequest webRequest = (HttpWebRequest)WebRequest
                                           .Create("http://www.gooogle.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
//Returns "MovedPermanently", not 301 which is what I want.
Console.Write(response.StatusCode.ToString());
6 Answers

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

Just coerce the StatusCode to int.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

Here's how i am handling such a situation.

//string details = ...
//...
catch (WebException ex)
{
    HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
    if (statusCode == HttpStatusCode.Unauthorized)
    {
        Reconnect();
        //...
    }
    else if (statusCode == HttpStatusCode.NotFound)
    {
        FileLogger.AppendToLog("[ERROR] Not Found: " + details);
    }
    else
    {
        FileLogger.AppendToLog("[ERROR] " + ex.Message + ": " + details);
    }
}
Related