Forcing C#'s HTTP Response to Return a Status Code Instead of a Description

I am currently using this script to get HTTP response headers.

public static List<string> GetHttpResponseHeaders(string url)
{
    List<string> headers = new List<string>();
    WebRequest webRequest = HttpWebRequest.Create(url);
    using (WebResponse webResponse = webRequest.GetResponse())
    {
        headers.Add("Status Code: " + (int) ((HttpWebResponse) webResponse).StatusCode);
    }
    return headers;
}

Specifically, Status Code: is what I am interested in. With that said, it appears that StatusCode() doesn't actually return a "status code," and on successful requests, it only returns an OK instead of a 200.

Is there a way to force it to return the actual code instead of a description?

Jon Skeet
people
quotationmark

With that said, it appears that StatusCode() doesn't actually return a "status code," and on successful requests, it only returns an OK instead of a 200.

No, it returns an HttpStatusCode enum value. If you call ToString on an enum value that has a name, it will return the name.

The simplest way of avoiding that is just to cast it to int:

headers.Add("Status Code: " + (int) ((HttpWebResponse) webResponse).StatusCode);

Or to make the rest of the block cleaner, cast the response once:

using (WebResponse webResponse = webRequest.GetResponse())
{
    var httpResponse = (HttpWebResponse) webResponse;
    headers.Add("URL: " + url);
    headers.Add("Status Code: " + (int) httpResponse.StatusCode);
    headers.Add("Status Description: " + httpResponse.StatusDescription + "\n");
}

(Note that when you're using string concatenation, ToString will be called implicitly if necessary - and it's never worth calling on something like StatusDescription which is already a string.)

people

See more on this question at Stackoverflow