C# 测试与网页的连接
我试图在我的代码中测试特定的网站是否可用C# 测试与网页的连接,c#,http,web,C#,Http,Web,我试图在我的代码中测试特定的网站是否可用 public override HealthCheckResult DoHealthCheck() { // Create a request using a URL that can receive a post. var request = (HttpWebRequest)WebRequest.Create(_healthCheckUrl); // Se
public override HealthCheckResult DoHealthCheck()
{
// Create a request using a URL that can receive a post.
var request = (HttpWebRequest)WebRequest.Create(_healthCheckUrl);
// Set the Method property of the request to POST.
request.Method = "GET";
request.Timeout = HealthCheckConfiguration.Timeout * 1000;\\Very Very large timeout
// Set the ContentType property of the WebRequest.
request.ContentType = "text/xml; encoding='utf-8'";
// Get the response.
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return HealthCheckResult.Success;
}
}
catch (WebException)
{
return HealthCheckResult.Timeout;
}
return HealthCheckResult.Failed;
}
有时我会得到HttpStatusCode.OK,但大多数时候我会得到超时异常。
如果我只是在internet explorer中复制粘贴_healthCheckUrl字符串,页面总是很快加载成功。我不明白为什么在代码中我有这么多的超时
提前谢谢 代码似乎假定任何WebException都是超时。这是实际抛出的异常吗?发生这种情况时,捕获WebException的详细信息是什么?提示:永远不要忽略异常。他们试图告诉你出了什么问题。你似乎总是假设WebException是一个超时-查看详细信息?你是对的,代码不清楚,但异常确实是超时,请参阅附加的异常:System.Net.WebException被捕获HResult=-2146233079 Message=操作已超时Source=System StackTrace:位于System.Net.HttpWebRequest.GetResponse位于DoHealthCheck第186行InnerException:如果您的URI无效,您将收到System.UriFormatException,您的代码中不会处理这些内容…URI在我的特定测试中确实有效,但我将修改代码以测试所有异常类型