繁体   English   中英

在c#(。net)system.net.http中,如何将response.statuscode作为int获取?不要使用HttpWebRequest和HttpWebResponse

[英]In c#( .net) system.net.http, how to get the response.statuscode as an int? Not to use HttpWebRequest and HttpWebResponse

        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,我该怎么办?

HttpResponseMessage.StatusCode是一个HttpStatusCode枚举,它的底层整数类型是int ,所以你可以把它强制转换:

int statusCode = (int)response.StatusCode;

HttpStatusCode声明为枚举类似:

enum HttpStatusCode
{
     NotFound = 404,
     ...
}

这意味着您只需通过投射即可完成:

int status = (int)HttpStatusCode.NotFound;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM