How to Refresh a token using IHttpClientFactory

Looks like you need DelegatingHandler. In two words you can “intercept” your http request and add the Authorization header, then try to execute it and if token was not valid, refresh token and retry one more time. Something like: public class AuthenticationDelegatingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var … Read more

Can I use HttpClientFactory in a .NET.core app which is not ASP.NET Core?

According to the documentation HttpClientFactory is a part of .Net Core 2.1, so you don’t need ASP.NET to use it. And there some ways to use are described. The easiest way would be to use Microsoft.Extensions.DependencyInjection with AddHttpClient extension method. static void Main(string[] args) { var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider(); var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>(); var … Read more

How to use HttpClientHandler with HttpClientFactory in .NET Core

More properly to define primary HttpMessageHandler via ConfigurePrimaryHttpMessageHandler() method of HttpClientBuilder. See example below to configure typed client how. services.AddHttpClient<TypedClient>() .ConfigureHttpClient((sp, httpClient) => { var options = sp.GetRequiredService<IOptions<SomeOptions>>().Value; httpClient.BaseAddress = options.Url; httpClient.Timeout = options.RequestTimeout; }) .SetHandlerLifetime(TimeSpan.FromMinutes(5)) .ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; }) .AddHttpMessageHandler(sp => sp.GetService<SomeCustomHandler>().CreateAuthHandler()) .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry) .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker); Also you can … Read more

How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

The HttpClientFactory is derived from IHttpClientFactory Interface So it is just a matter of creating a mock of the interface var mockFactory = new Mock<IHttpClientFactory>(); Depending on what you need the client for, you would then need to setup the mock to return a HttpClient for the test. This however requires an actual HttpClient. var … Read more

Should HttpClient instances created by HttpClientFactory be disposed?

Calling the Dispose method is not required but you can still call it if you need for some reasons. Proof: HttpClient and lifetime management Disposal of the client isn’t required. Disposal cancels outgoing requests and guarantees the given HttpClient instance can’t be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances. … Read more