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

六眼飞鱼酱① 提交于 2019-12-10 21:46:30

问题


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?


回答1:


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




回答2:


StatusCode is an HttpStatusCode enum.

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




回答3:


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.



来源:https://stackoverflow.com/questions/21607706/forcing-cs-http-response-to-return-a-status-code-instead-of-a-description

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!