Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate timeouts for connection and response on HttpClient

There are multiple ways for HttpClient calls to timeout/be cancelled: by setting the HttpClient.Timeout property, by passing in a CancellationToken, using a custom HttpMessageHandler, etc. The problem with all these approaches is that the timeout is met and the call is cancelled regardless of if the server couldn't be reached at all or if it just takes longer to respond.

An existing example of the behavior I want to implement is Postman:
When (for this example) my ASP.NET Core Web API is not currently running and I send a request via Postman it stops right after just 5 seconds or so. But when my Web API runs, I send a request via Postman and then hit a breakpoint in my code or add a delay or something, than Postman will wait the amount of milliseconds that was specified in its settings (= more than 5 seconds).

And that's kind of what I want to get to work. To have two different timeouts for my HTTP requests. One for waiting for a connection to the server and one for waiting for its response. Perfect would be if the call would also be cancelled when the connection to the server is interrupted while waiting for the response. Is something like this possible in C# (using .NET 6) and if yes, how?

like image 876
Christoph Mett Avatar asked Feb 26 '26 00:02

Christoph Mett


1 Answers

When instantiating HttpClient, you're able to provide an implementation of System.Net.Http.HttpMessageHandler, I believe the default implementation is SocketsHttpHandler.

On the SocketsHttpHandler you're able to provide a connection timeout.

var handler = new SocketsHttpHandler
{
    ConnectTimeout = TimeSpan.FromSeconds(5)
};

var client = new HttpClient(handler);

// stuff as usual...

I prefer this to using a sanity check as there's no guarantee that if the first call succeeds that the second one will.

like image 137
Matthew Avatar answered Feb 28 '26 13:02

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!