开发者

Checking website status in .NET

开发者 https://www.devze.com 2022-12-08 23:50 出处:网络
I need to buil开发者_JAVA百科d a .NET function that tests to see if a specific website is online.What is the best way to do this?I was going to simply ping the site, but I wondered if there was a more

I need to buil开发者_JAVA百科d a .NET function that tests to see if a specific website is online. What is the best way to do this? I was going to simply ping the site, but I wondered if there was a more accurate method.

Thanks!


I always use this for checking if websites are working correctly:

public bool IsWebsiteOnline(string url)
{
    try
    {
        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
        myReq.Timeout = 10000;

        using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse()) 
        {
           return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
        return false;
    }
}


Never assume the ability to ping a site gives you any information about the status of it, other than the box is turned on and happens to respond to pings.


A ping checks that the server responds. However the web app part could be down, the db could be done, etc etc.

SO writing a request for HTTP data from the URL, and :

1) check the status code response is OK

2) check there was content at all (non empty page)

*3) if you really want to be clever, depending on requirements, validate the data returned - ie compare part of it for a particular string.

*but at a bare minimum I'd suggest 1 and 2.


You could use Watin to perform small tasks and thereby judge if the site is working properly.

Watin allows you to test functionality as well.
(Some code stolen from their site)

public void SearchForWatiNOnGoogle()
{
 using (IE ie = new IE("http://www.google.com"))
 {
  ie.TextField(Find.ByName("q")).TypeText("WatiN");
  ie.Button(Find.ByName("btnG")).Click();

  Assert.IsTrue(ie.ContainsText("WatiN"));
 }
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消