
The helper method will throw HttpRequestException with StatusCode set if it wasn't 2xx. The exception filtering for those calls then looks like this: class Program Since HttpClient helper methods: GetStringAsync, GetByteArrayAsync and GetStreamAsync do not return HttpResponseMessage, they call EnsureSuccessStatusCode themselves.


Using var response = await _client.GetAsync(" // The following line will throw HttpRequestException with StatusCode set if it wasn't 2xx.Ĭatch (HttpRequestException ex) when (ex.StatusCode = HttpStatusCode.NotFound)Ĭonsole.WriteLine("Not found: " + ex.Message) Private static readonly HttpClient _client = new HttpClient() Then it can be used in exception filters: class Program The new StatusCode property is nullable set when EnsureSuccessStatusCode is called on the response. Using var response = await _client.GetAsync(" }Ĭatch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)Īnother improvement was to add HttpStatusCode to HttpRequestException ( #911). With this change, the client still throws TaskCanceledException (for backward compatibility), but the inner exception is a TimeoutException in case of a timeout: class Program If the token has been canceled, it is not a timeout.Ĭatch (TaskCanceledException ex) when (cts.IsCancellationRequested)Ĭonsole.WriteLine("Canceled: " + ex.Message) Ĭonsole.WriteLine("Timed out: "+ ex.Message) Using var response = await _client.GetAsync(" cts.Token) Originally, a custom CancellationToken had to be used to distinguish a timeout from a cancellation: class Program One of the most requested was to add the ability to distinguish timeouts from cancellations when using HttpClient ( #21965).

NET Core 3.1 was released, many improvements and fixes have been made in the HTTP space. In this post, I will highlight some of the more impactful and interesting changes in the release. This includes improvements around HTTP, Sockets, networking-related security, and other networking primitives. NET 5 released in November, it’s a good time to talk about some of the many improvements in the networking stack.
