【问题标题】:How to see if HttpClient connects to offline website如何查看 HttpClient 是否连接到离线网站
【发布时间】:2014-02-03 14:34:42
【问题描述】:
所以我正在关注本教程:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client,我想知道如何查看我连接的网站是否离线。
这是我得到的代码
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54932/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/products").Result;
Console.WriteLine("here");
当 URL http://localhost:54932/ 在线时,一切正常,并打印 here。然而,当网站离线时,here 不会打印出来。如何知道 ip 地址是否已关闭?
【问题讨论】:
标签:
c#
asp.net-web-api
webclient
【解决方案1】:
您应该设置一个超时以了解网站是否已启动。
来自here 的示例:
// Create an HttpClient and set the timeout for requests
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(10);
// Issue a request
client.GetAsync(_address).ContinueWith(
getTask =>
{
if (getTask.IsCanceled)
{
Console.WriteLine("Request was canceled");
}
else if (getTask.IsFaulted)
{
Console.WriteLine("Request failed: {0}", getTask.Exception);
}
else
{
HttpResponseMessage response = getTask.Result;
Console.WriteLine("Request completed with status code {0}", response.StatusCode);
}
});