My service definition:
var host = new HostBuilder().ConfigureServices(services =>
{
services
.AddHttpClient<Downloader>()
.AddPolicyHandler((services, request) =>
HttpPolicyExtensions
.HandleTransientHttpError()
.Or<SocketException>()
.Or<HttpRequestException>()
.WaitAndRetryAsync(
new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10) },
onRetry: (outcome, timespan, retryAttempt, context) =>
{
Console.WriteLine($"Delaying {timespan}, retrying {retryAttempt}.");
}));
services.AddTransient<Downloader>();
}).Build();
Implementation of the Downloader
:
class Downloader
{
private HttpClient _client;
public Downloader(IHttpClientFactory factory)
{
_client = factory.CreateClient();
}
public Download()
{
await _client.GetAsync(new Uri("localhost:8800")); // A port that no application is listening
}
}
With this setup, I expect to see three attempts of querying the endpoint, with the logging message printed to the console (I've also unsuccessfully tried with a logger, using the console for simplicity here).
Instead of the debugging messages, I see the unhandled exception message (which I only expect to see after the retries and the printed logs).
Unhandled exception: System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (127.0.0.1:8800) ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.