Search code examples
c#system.net.httpwebrequest

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();

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


Solution

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

    int statusCode = (int)response.StatusCode;