2014-01-15 89 views
0

因此,我正在关注本教程:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client,我想知道我如何查看我连接到的网站是否处于离线状态。如何查看HttpClient是否连接到离线网站

这是我有

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地址是否已关闭?

回答

2

你应该设置一个超时时间来知道网站是否启动。

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); 
      } 
    }); 
+0

大非常感谢! – user3182508

相关问题