强制C#的HTTP响应返回状态代码而不是描述

编程入门 行业动态 更新时间:2024-10-06 04:07:50
本文介绍了强制C#的HTTP响应返回状态代码而不是描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用此脚本来获取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?

推荐答案

话虽如此,看来StatusCode()实际上并没有返回状态码",并且在成功请求时,它仅返回OK而不是200.

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.

否,它将返回 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响应返回状态代码而不是描述

本文发布于:2023-11-12 20:58:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582515.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   状态   代码   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!