Test if a website is alive from a C# application

I am looking for the best way to test if a website is alive from a C# application.

Background

My application consists of a Winforms UI, a backend WCF service and a website to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of a missing WCF service or website being down I have added an app startup check to ensure that all everything is alive.

The application is being written in C#, .NET 3.5, Visual Studio 2008

Current Solution

Currently I am making a web request to a test page on the website that will inturn test the web site and then display a result.

WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");
WebResponse response = request.GetResponse();

I am assuming that if there are no exceptions thown during this call then all is well and the UI can start.

Question

Is this the simplest, right way or is there some other sneaky call that I don't know about in C# or a better way to do it.


Solution 1:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)

As @Yanga mentioned, HttpClient is probably the more common way to do this now.

HttpClient client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (!checkingResponse.IsSuccessStatusCode)
{
   return false;
}

Solution 2:

While using WebResponse please make sure that you close the response stream ie (.close) else it would hang the machine after certain repeated execution. Eg

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
// your code here
response.Close();

Solution 3:

from the NDiagnostics project on CodePlex...

public override bool WebSiteIsAvailable(string Url)
{
  string Message = string.Empty;
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);

  // Set the credentials to the current user account
  request.Credentials = System.Net.CredentialCache.DefaultCredentials;
  request.Method = "GET";

  try
  {
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
      // Do nothing; we're only testing to see if we can get the response
    }
  }
  catch (WebException ex)
  {
    Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
  }

  return (Message.Length == 0);
}

Solution 4:

We can today update the answers using HttpClient():

HttpClient Client = new HttpClient();
var result = await Client.GetAsync("https://stackoverflow.com");
int StatusCode = (int)result.StatusCode;