Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
theGreenCabbage Avatar asked Feb 22 '26 23:02

theGreenCabbage


1 Answers

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

like image 102
Jon Skeet Avatar answered Feb 24 '26 11:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!