Posts

Showing posts with the label HttpClient

Implement timeout and retry policies for HttpClient in ASP NET Core with Polly

Implement timeout and retry policies for HttpClient in ASP NET Core with Polly Few weeks ago I explained [how to use the new HttpClientFactory . This freed ourselves from managing the confusing lifecycle of a HttpClient and at the same time allowed us to setup commmon options like base address for all HttpClient injections in our classes. Today we will see how we can setup timeout and retry policies for the HttpClient in in ASP NET Core using Polly . Setup a simple service using HttpClient Install Polly extensions for ASP NET Core Setup Polly policies 1. Setup a simple service using HttpClient In the previous blog post we saw how we could setup a HttpClient and register it to the service collection. Here is a simple service client which will be injected throughout the application: public interface IMyApiClient { Task<HttpResponseMessage> Get(); } And here is the implementation: public class MyApiClient : IMyApiClient { private readonly HttpClient _client; ...

HttpClientFactory in ASP NET Core 2.1

HttpClientFactory in ASP NET Core 2.1 ASP.NET Core 2.1 ships with a factory for HttpClient called HttpclientFactory . This factory allows us to no longer care about the lifecycle of the HttpClient by leaving it to the framework. Today we will see few ways of instantiating clients: Default client Typed client Named client 1. Default client To use the factory, we start first by registering it to the service collection with .AddHttpClient() which is an extension coming from Microsoft.Extensions.Http . public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddHttpClient(); } This gives us access to the IHttpClientFactory which we can inject and using it, we can create a HttpClient . [HttpPost] public async Task<ActionResult<string>> PostDefaultClient([FromServices]IHttpClientFactory factory, [FromBody] ValueDto value) { var client = factory.CreateClient(); client.BaseAddress = new System.Uri("http://loc...