KT-Guy
KT-Guy

Reputation: 53

HttpClient and Exception Handling

HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };

HttpClient client = new HttpClient(httpClientHandler);
client.BaseAddress = new Uri(url);

try
{

    client.Timeout = TimeSpan.FromSeconds(30);
    var response = await client.PostAsync(uri, content);


     if (response.IsSuccessStatusCode)
     {
        // do something
     }

}
catch (HttpRequestException ex)
{
    // do error stuff
}
catch (TaskCanceledException ex)
{
    // do error stuff #2
}
catch (Exception ex)
{
    // do error stuff #3
}

I am new to HttpClient.

During our test, we shut down the web service that this code is hitting in order to test this block of code. (BTW, it works as expected when the web service is running.)

Why does it take 2 minutes and 10 sec instead of 30 seconds to hit the TaskCanceledException catch?

Upvotes: 2

Views: 2288

Answers (1)

Peter Csala
Peter Csala

Reputation: 22714

The default timeout for HttpClient is 100 seconds. The observed 130 seems pretty strange.

If you run the following code inside dotnet fiddle, then you would see it does cancel the request after 2 seconds and will not wait for a response for 5 seconds:

using System;
using System.Net.Http;
using System.Threading.Tasks;
                    
public class Program
{
    public static async Task Main()
    {
        var handler = new HttpClientHandler();
        var client = new HttpClient(handler);
        client.BaseAddress = new Uri("https://httpstat.us");
        client.Timeout = TimeSpan.FromSeconds(2);

        try 
        {
            _ = await client.GetAsync("/200?sleep=5000");
        }
        catch (OperationCanceledException)
        {
            "Timed out".Dump();
            Environment.Exit(-1);
        }
        "Finished".Dump();
    }
}

Upvotes: 1

Related Questions