Get the HTTP status code from a URL

Dec 13, 2006

Yesterday, I wrote about the Ping class for checking network availability on remote machines. Then I started thinking about checking the availability of web servers. Even if a remote server is available over the network, the web server instance might not response to requests so we need another method to check if it’s responding correctly.

What we really want is not a Boolean value telling us if the web server is responding or not. The best way is to get the HTTP status code so we can act appropriately. The status code for a properly working web server is 200 and 404 if there is no reply. There are a lot of other codes that we can act differently upon as we please. Here’s a list of possible status codes.

This static method returns a System.Net.HttpStatusCode enumeration value based on the specified URL.

private static HttpStatusCode HttpStatus(string url)

{

  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

 

  try

  {

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

    {

      return response.StatusCode;

    }

  }

  catch (System.Net.WebException)

  {

    return HttpStatusCode.NotFound;

  }

}

You can use it to write the status code to the response stream like this:

Response.Write((int)HttpStatus("http://www.google.com"));

By using this simple method it is very easy to build your own web server checking tool. If you want to run multiple URL checks from ASP.NET, it would be a good idea to use ASP.NET 2.0’s possibility for asynchronous processing for improved performance in situations where you are creating web requests.

* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (2) -

 Mike
Mike
12/18/2006 12:39:38 PM #

I ran into an interesting situation with code similar to this. Namely, the status code 403 - Forbidden. If you query a site that returns a 403 code, HttpWebResponse raises a System.Net.WebException. It does the same for other failure codes as well. Not what I would expect.

Gord
Gord
2/7/2007 4:24:49 PM #

Ditto for a 401 error.  Exception raised and the only way to get the status code that I can find is to search the exception message for a number.  Any better ideas?

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.