

Nothing fancy here, the timeout is an optional value of type TimeSpan. Public static TimeSpan? GetTimeout( this HttpRequestMessage request) Throw new ArgumentNullException(nameof(request)) Private static string TimeoutPropertyKey = "RequestTimeout" Public static class HttpRequestExtensions We’re going to use this to store the timeout for a request, and to make things easier, we’ll create extension methods to access the value in a strongly-typed fashion: The HttpRequestMessage class has a Properties property, which is a dictionary in which we can put whatever we need. Let’s see how we can associate a timeout value to a request. Specifying the timeout on a per-request basis to receive a TimeoutException rather than a TaskCanceledException when a timeout occurs.the ability to specify timeout on a per-request basis.So we’re going to implement a workaround for these two issues. When a timeout occurs, you’d expect to get a TimeoutException, right? Well, surprise, it throws a TaskCanceledException! So, there’s no way to tell from the exception if the request was actually canceled, or if a timeout occurred.įortunately, thanks to HttpClient’s flexibility, it’s quite easy to make up for this design flaw. The exception thrown when the timeout is elapsed doesn’t let you determine the cause of the error.The timeout is defined at the HttpClient level and applies to all requests made with this HttpClient it would be more convenient to be able to specify a timeout individually for each request.There are two major issues with timeout handling in HttpClient: If you often use HttpClient to call REST APIs or to transfer files, you may have been annoyed by the way this class handles request timeout.
