.NET: Check URL's response status code?

Viewed 36810

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 possible, only the header should be requested. Having said that, however, if requesting that the body of the response be omitted significantly increases the complexity of the code, receiving the body would be fine.

Also, I'm particularly interested in catching ALL the possible appropriate exceptions (System.Net.WebException, System.IO.IOException, System.Net.Sockets.SocketException, etc.), as this routine will run thousands of times a day.

6 Answers

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

WebRequest is obsolete, use HttpClient instead:

public async static Task<HttpStatusCode> GetStatusCode(string url)
{
    using var client = new HttpClient();
    var res = await client.GetAsync(url);
    return res.StatusCode;
}
Related