Question

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?

Was it helpful?

Solution

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.)

OTHER TIPS

StatusCode is an HttpStatusCode enum.

You can cast it to int to get the underlying value.

The reason you're seeing the value "OK" is because property HttpWebResponse.StatusCode is of type HttpStatusCode - an enumeration. Calling .ToString() on an enumeration will give you text, not a number.

So, while you're not seeing the numeric value of the status code, you are seeing a representation of the status code, and not the status description.

If you need the integer value, you can cast the enum to int (HttpStatusCode.OK does indeed have a value of 200) - but it's worth considering that there's no guarantee that the integer values of the enum will line up with the status code values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top