问题
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