从 C# 应用程序测试网站是否有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/186894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if a website is alive from a C# application
提问by FryHard
I am looking for the best way to test if a website is alive from a C# application.
我正在寻找从 C# 应用程序测试网站是否存在的最佳方法。
Background
背景
My application consists of a Winforms UI, a backend WCF serviceand a websiteto 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.
我的应用程序由一个Winforms UI、一个后端WCF 服务和一个网站组成,用于向 UI 和其他消费者发布内容。为了防止 UI 启动并由于缺少 WCF 服务或网站关闭而无法正常工作的情况,我添加了一个应用程序启动检查以确保所有一切都处于活动状态。
The application is being written in C#, .NET 3.5, Visual Studio 2008
该应用程序是用 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.
我假设如果在此调用期间没有异常,那么一切都很好并且 UI 可以启动。
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.
这是最简单、正确的方法,还是我在 C# 中不知道的其他一些偷偷摸摸的调用或更好的方法。
采纳答案by Echostorm
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.
正如@Yanga 提到的,HttpClient 可能是现在更常用的方法。
HttpClient client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (!checkingResponse.IsSuccessStatusCode)
{
return false;
}
回答by Robert Rouse
You'll want to check the status code for OK (status 200).
您需要检查状态代码是否为 OK(状态 200)。
回答by Sklivvz
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:
假设 WCF 服务和网站位于同一个 Web 应用程序中,您可以使用返回应用程序状态的“状态”WebService。您可能想要执行以下一些操作:
- 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.
- 测试数据库是否已启动并正在运行(良好的连接字符串、服务已启动等...)
- 测试网站是否正常工作(具体取决于网站)
- 测试 WCF 是否正常工作(具体取决于您的实现)
- 额外的好处:如果您将来需要支持不同的版本,您可以返回有关该服务的一些版本信息。
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.
然后,您在 Win.Forms 应用程序上为 WebService 创建一个客户端。如果 WS 没有响应(即您在调用时遇到一些异常),则该网站已关闭(如“一般错误”)。
如果 WS 响应,您可以解析结果并确保一切正常,或者如果出现问题,则返回更多信息。
回答by ZombieSheep
from the NDiagnosticsproject on CodePlex...
来自CodePlex 上的NDiagnostics项目...
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);
}
回答by 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
在使用 WebResponse 时,请确保关闭响应流,即 (.close),否则它会在某些重复执行后挂起机器。例如
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
// your code here
response.Close();
回答by NoloMokgosi
Solution from: How do you check if a website is online in C#?
解决方案来自:如何在 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;
回答by Yanga
We can today update the answers using HttpClient():
我们今天可以使用HttpClient()更新答案:
HttpClient Client = new HttpClient();
var result = await Client.GetAsync("https://stackoverflow.com");
int StatusCode = (int)result.StatusCode;