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

时间:2015-09-02 07:59:37

标签: c# system.net.httpwebrequest

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

2 个答案:

答案 0 :(得分:3)

HttpResponseMessage.StatusCode是一个HttpStatusCode枚举,其基础整数类型为int,因此您只需将其转换为:

int statusCode = (int)response.StatusCode;

答案 1 :(得分:3)

HttpStatusCode被声明为枚举类似:

enum HttpStatusCode
{
     NotFound = 404,
     ...
}

这意味着你可以通过施放来实现:

int status = (int)HttpStatusCode.NotFound;