.NET: Check URL’s response status code?

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

public HttpStatusCode GetHeaders(string url)
        HttpStatusCode result = default(HttpStatusCode);

        var request = HttpWebRequest.Create(url);
        request.Method = "HEAD";
        using (var response = request.GetResponse() as HttpWebResponse)
            if (response != null)
                result = response.StatusCode;

        return result;

Use the HTTP method HEAD, which is the same as GET except doesn’t return the body:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Method = "HEAD";
var response = (HttpWebResponse)request.GetResponse();

// status code...

If you use HttpWebRequest, it’s pretty easy:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://url");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode status = response.StatusCode;

You can surround that with a blanket catch clause, or look at the docs for WebRequest.Create and .GetResponse to see what exceptions will get thrown.

I’ve ended up with this method which combines Ivan Ferić’s answer and with proper exceptional cases support:

public async Task<bool> IsAccessibleAsync (string url)
    if (url == null)
        throw new ArgumentNullException ("url");

    if (url.IndexOf (':') < 0)
        url = "http://" + url.TrimStart ('/');

    if (!Uri.IsWellFormedUriString (url, UriKind.Absolute))
        return false;

    var request = (HttpWebRequest) WebRequest.Create (url);
    request.Method = "HEAD";

        using (var response = await request.GetResponseAsync () as HttpWebResponse)
            if (response != null && response.StatusCode == HttpStatusCode.OK)
                return true;

            return false;
    catch (WebException)
        return false;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s