54

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.

Community
  • 1
  • 1
FryHard
  • 10,305
  • 7
  • 35
  • 38

7 Answers7

94
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;
}
Echostorm
  • 9,678
  • 8
  • 36
  • 50
  • 2
    Will this work for any site ? Like i am making something similar where it give error on some site but when i put the url in browser it opens fine. – confusedMind Mar 20 '14 at 05:58
  • 2
    @confusedMind It could be that the server is returning a code other than a 200 OK status code. If you look at the list of [HTTP Status codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) you'll notice that all 200,300 http codes aren't error codes so in a browser might still load the page as if its fine. – clifford.duke Mar 21 '14 at 07:12
  • 2
    HTTP 500s will throw exceptions, so the existing check isn't enough. Have a look at the following for catching the exception, and checking the HTTP status code: http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba for – Overflew Jul 07 '15 at 22:41
  • I think this solution returns requested URL body! How can we only check a URL is alive or not? – Mohammad Afrashteh May 25 '18 at 16:47
  • @MohammadAfrashteh You need to get the response to be sure, something simpler like a ping could lead to a false positive as the server could be online but not serving pages. – Echostorm May 30 '18 at 12:40
  • OK. But if the requested page body is large (e.g: 100MB <) it is an unreasonable way to be sure! Getting head of the requested resource will be enough to be sure. – Mohammad Afrashteh May 30 '18 at 13:44
  • @MohammadAfrashteh I can't say that I've ever encountered a 100MB page or anything even close to that but if it is that important to you, I think if you set request.Method = "HEAD" before calling GetResponse it will not return the content. I hope that helps. – Echostorm May 31 '18 at 12:59
21

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();
Ole Albers
  • 8,715
  • 10
  • 73
  • 166
Maxymus
  • 1,460
  • 2
  • 14
  • 22
10

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);
}
ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
8

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;
Yanga
  • 2,885
  • 1
  • 29
  • 32
3

Assuming the WCF service and the website live in the same web app, you can use a "Status" WebService that returns the application status. You probably want to do some of the following:

  • Test that the database is up and running (good connection string, service is up, etc...)
  • Test that the website is working (how exactly depends on the website)
  • Test that WCF is working (how exactly depends on your implementation)
  • Added bonus: you can return some versioning info on the service if you need to support different releases in the future.

Then, you create a client on the Win.Forms app for the WebService. If the WS is not responding (i.e. you get some exception on invoke) then the website is down (like a "general error").
If the WS responds, you can parse the result and make sure that everything works, or if something is broken, return more information.

Sklivvz
  • 30,601
  • 24
  • 116
  • 172
  • They are unfortunately not in the same web app, but this is not too much of a problem. I have already created all the tests for the DB and the ORM :) (but thanx for the suggestion) – FryHard Oct 09 '08 at 12:06
  • real world samples about it ? ***test database, website, WCF, versioning*** – Kiquenet Aug 03 '18 at 07:20
-3

You'll want to check the status code for OK (status 200).

Robert Rouse
  • 4,801
  • 1
  • 19
  • 19
-3

Solution from: How do you check if a website is online in C#?

var ping = new System.Net.NetworkInformation.Ping();

var result = ping.Send("https://www.stackoverflow.com");

if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
    return;
NoloMokgosi
  • 1,678
  • 16
  • 10
  • 4
    This only pings the server, i.e. checks to see if the machine is up and running. It doesn't check if the server respond with information on port 80. – Karlth Aug 14 '15 at 16:12