user3182508
user3182508

Reputation: 139

How to see if HttpClient connects to offline website

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?

Upvotes: 1

Views: 2962

Answers (1)

MathB.Fr
MathB.Fr

Reputation: 292

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

Upvotes: 4

Related Questions