This small application is an example to use the built-in HttpClientFactory in ASP.NET Core.
Separate branch with the .NET Core 2.2 version.
HttpClientFactory
provides a central location to configure and createHttpClient
instances.
- Some blog posts about HttpClientFactory πSteve Gorgon
- Letβs talk about HTTP in .NET Core π½οΈ45min - Steve Gorgon
- You are (probably) using HttpClient wrong πJosef Ottosson
- Customize the HttpClient logging πJosef Ottosson
- The right way to use HttpClient πMilan's newsletter
- How to mock HttpClient in unit tests πGingter Ale
- Delegating handlers to extend HttpClient πCode-Maze
- Using Moq and Moq.Protected
- Using the MockHttp package π€Richard Szalay
- Using the Pact. NET package π€Pact Foundation
- Using WireMock.Net π€package
- Seamless Integration Testing with WireMock.NET πCode-Maze
- Introduction πCezary PiΔ tek
- Troubleshooting - WireMockInspector πCezary PiΔ tek
- Why my WireMock mocks aren't working? πDaniel Genezini
-
Using Polly as a resilience and transient-fault-handling library, which can helps you to easily write retry logic. Other useful information: Polly and HttpClientFactory.
-
In the example, I use a timeout policy to cancel a long running call. You can find a solution to use
CancellationToken
in case, if the client side application cancel the request.
You can find a similar example in this repository: Playing with Refit. Automatic type-safe REST library to initiate http calls.
In the example, I did not use the Flurl as fluent URL builder and HTTP client library. Worth to check the following article: Consuming GitHub API (REST) With Flurl.
public void ConfigureServices(IServiceCollection services)
{
// Add: MessageHandler(s) to the DI container.
services.AddTransient<TestMessageHandler>();
// Create: Polly policy
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>() // Thrown by Polly's TimeoutPolicy if the inner call gets timeout.
.WaitAndRetryAsync(_wrc.Retry, _ => TimeSpan.FromMilliseconds(_wrc.Wait));
AsyncTimeoutPolicy<HttpResponseMessage> timeoutPolicy = Policy
.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromMilliseconds(_wrc.Timeout));
// Add your service/clients with an interface, helps you to make your business logic testable.
// --> Add: HttpClient + Polly WaitAndRetry for HTTP 5xx and 408 responses.
services.AddHttpClient<IUserClient, UserHttpClient>()
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(timeoutPolicy) // The order of adding is imporant!
// Add: MessageHandler(s).
.AddHttpMessageHandler<TestMessageHandler>();
}