测试网站是否在C#应用程序中仍然存在 [英] Test if a website is alive from a C# application

查看:52
本文介绍了测试网站是否在C#应用程序中仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找测试网站是否在C#应用程序中存活的最佳方法。

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

我的应用程序由一个 Winforms UI ,后端 WCF服务网站,用于将内容发布到UI和其他使用者。为了防止由于缺少WCF服务或网站关闭而导致UI启动并无法正常工作的情况,我添加了应用启动检查,以确保所有功能均有效。

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.

该应用程序是用C#、. NET 3.5,Visual Studio 2008编写的。

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

当前,我正在向测试页面发出Web请求在网站上会依次测试该网站,然后显示结果。

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

我假设如果在此调用过程中没有抛出异常,那么一切都很好,UI可以启动。

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

这是最简单,正确的方法吗?还是在C#中我不知道的其他偷偷摸摸的电话还是更好的方法

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.

推荐答案

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

如@Yanga所述,HttpClient可能是现在更常用的方法。

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

这篇关于测试网站是否在C#应用程序中仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆