Test if a website is alive from a C# application

做~自己de王妃 提交于 2019-11-26 21:43:22
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)
Maxymus

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();

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);
}

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.

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;

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

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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!