Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a website is alive from a C# application

Tags:

c#

webrequest

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.

like image 255
FryHard Avatar asked Oct 09 '08 11:10

FryHard


3 Answers

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;
}
like image 69
Echostorm Avatar answered Nov 17 '22 15:11

Echostorm


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();
like image 35
Maxymus Avatar answered Nov 17 '22 16:11

Maxymus


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);
}
like image 10
ZombieSheep Avatar answered Nov 17 '22 17:11

ZombieSheep