Microsoft.Extensions.Http.Polly integrates Polly resilience policies with HttpClient instances created by IHttpClientFactory. It handles transient failures in the handler pipeline, so callers can use a resilient client without writing retry logic manually. section 33.3
Configure transient HTTP error handling in a few steps:
- Install the Microsoft.Extensions.Http.Polly NuGet package. section 33.3
- Register a named or typed client with AddHttpClient. section 33.3
- Call AddTransientHttpErrorPolicy and provide a Polly policy, such as a retry policy waiting 200 milliseconds, 500 milliseconds, and one second between attempts. section 33.3
- Review retry effects carefully: default handling covers connection errors, 5xx responses, and 408 timeouts, but retries should target only safe requests. section 33.5
Retrying an ExchangeRatesClient request
builder.Services.AddHttpClient<ExchangeRatesClient>() .AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(new[] { TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1) })); If a transient network problem or server error occurs, the handler retries before returning failure to the caller. section 33.3
Figure 33.5 Using the PolicyHttpMessageHandler to handle transient errors. If an error occurs when calling the remote API, the Polly handler will automatically retry the request. If the request then succeeds, the result is passed back to the caller. The caller didn’t have to handle the error, making it simpler to use the HttpClient while remaining resilient to transient errors.
Shows how PolicyHttpMessageHandler retries a failed remote request and passes a successful result back through the HttpClient pipeline. section 33.3
