问题描述
我目前正在使用此脚本来获取HTTP响应标头.
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;
}
具体来说,Status Code:
是我感兴趣的.如此说来,看来StatusCode()
实际上并没有返回状态码",并且在成功请求时,它仅返回了OK
而不是一个200
.
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?
推荐答案
否,它将返回 HttpStatusCode
枚举值.如果对具有名称的枚举值调用ToString
,它将返回名称.
No, it returns an HttpStatusCode
enum value. If you call ToString
on an enum value that has a name, it will return the name.
避免这种情况的最简单方法是将其强制转换为int
:
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");
}
(请注意,当您使用字符串连接时,如有必要,将隐式调用ToString
,这绝对不值得调用已经为字符串的StatusDescription
之类的东西.)
(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.)
这篇关于强制C#的HTTP响应返回状态代码而不是描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!