在c#(.net)system.net.http中,如何将response.statuscode获取

In c#( .net) system.net.http, how to get the response.statuscode as an int? Not to use HttpWebRequest and HttpWebResponse
2020-09-18
  •  译文(汉语)
  •  原文(英语)
        var hcHandler = new HttpClientHandler();
        //hcHandler.AllowAutoRedirect = false;
        var hc = new HttpClient(hcHandler);
        hc.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
        String url = "http://passport.cnblogs.com/login.aspx";
        var task = hc.GetAsync(new Uri(url));
        HttpResponseMessage response = task.Result;

        string statusCode = response.StatusCode.ToString();

我想以整数获取statusCode,该怎么办?

解决过程1

HttpResponseMessage.StatusCode是一个HttpStatusCode枚举,其基础整数类型为int,因此可以将其强制转换为:

int statusCode = (int)response.StatusCode;
解决过程2

HttpStatusCode 声明为枚举,类似于:

enum HttpStatusCode
{
     NotFound = 404,
     ...
}

这意味着您可以简单地通过以下方式进行操作:

int status = (int)HttpStatusCode.NotFound;
        var hcHandler = new HttpClientHandler();
        //hcHandler.AllowAutoRedirect = false;
        var hc = new HttpClient(hcHandler);
        hc.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
        String url = "http://passport.cnblogs.com/login.aspx";
        var task = hc.GetAsync(new Uri(url));
        HttpResponseMessage response = task.Result;

        string statusCode = response.StatusCode.ToString();

I want to get the statusCode in integer, how can I do?

Solutions1

HttpResponseMessage.StatusCode is a HttpStatusCode enum, whose underlying integer type is int, so you can just cast it:

int statusCode = (int)response.StatusCode;
Solutions2

HttpStatusCode is declared as an enum sort of like:

enum HttpStatusCode
{
     NotFound = 404,
     ...
}

Which means you can do it simply by casting:

int status = (int)HttpStatusCode.NotFound;
转载于:https://stackoverflow.com/questions/32347632/in-c-net-system-net-http-how-to-get-the-response-statuscode-as-an-int-not

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入