How to see if HttpClient connects to offline website

佐手、 提交于 2019-12-13 05:24:28

问题


So I'm following this tutorial: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client and I wonder how I can see whether the website where I connect to is offline.

This is the code I've got

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

When the url http://localhost:54932/ is online everything works just fine, and here is printed. Yet when the website is offline, the here is not printed. How can I know if the ip adres is down?


回答1:


You should set a timeout in order to know if the website is up.

An example from 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);
            }
    });


来源:https://stackoverflow.com/questions/21132093/how-to-see-if-httpclient-connects-to-offline-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!