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

James Lawruk picture James Lawruk · Aug 25, 2009 · Viewed 303k times · Source

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());

Answer

dtb picture dtb · Aug 25, 2009
Console.Write((int)response.StatusCode);

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}