Search code examples
c#.nethttp.net-core.net-6.0

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?


Solution

  • Looks like you can achieve what you want by passing an instance SocketsHttpHandler of to the constructor of HttpClient.

    SocketsHttpHandler has a ConnectTimeout property which will cause a timeout in HttpClient if a connection is not established before the specified duration elapses.

    See the official Microsoft documentation on setting Timeouts in HttpClient for more details.