.NET: Check URL's response status code?

后端 未结 5 2189
时光说笑
时光说笑 2021-02-18 18:36

What\'s the easiest way in .NET to check what status code a web server replies with to a GET request?

Note that I do not need the body of the response. In fact, if possi

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 18:57

    Here is what I came up with that handles 404 exceptions. There is also a test below.

    public static HttpStatusCode GetUrlStatus(string url, string userAgent)
    {
        HttpStatusCode result = default(HttpStatusCode);
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.UserAgent = userAgent;
        request.Method = "HEAD";
    
        try
        {
            using (var response = request.GetResponse() as HttpWebResponse)
            {
                if (response != null)
                {
                    result = response.StatusCode;
                    response.Close();
                }
            }
        }
        catch (WebException we)
        {
            result = ((HttpWebResponse)we.Response).StatusCode;
        }
    
        return result;
    }
    
    
    [Test]
    public void PageNotFoundShouldReturn404()
    {
        //Arrange
        HttpStatusCode expected = HttpStatusCode.NotFound;
        string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
    
        //Act
        HttpStatusCode result = WebHelper.GetUrlStatus("http://www.kellermansoftware.com/SomePageThatDoesNotExist", userAgent);
    
        //Assert
        Assert.AreEqual(expected, result);
    }   
    

提交回复
热议问题