Using HttpClient in c# with auto retry

http

HttpClient is designed to be used as a single instance across multiple requests and threads.

Here we create a custom handler that attempts to send a request until a successful response is received


public class RetryHandler : DelegatingHandler
{

    public int DelaySeconds { get; set; } = 5;
    public int MaxRetries { get; set; } = 3;
    
    public RetryHandler(HttpMessageHandler innerHandler)
    : base(innerHandler)
    { }
    
    protected override async Task<HttpResponseMessage> SendAsync(
    	HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;
        for (int i = 0; i < MaxRetries; i++)
        {
        	response = await base.SendAsync(request, cancellationToken);
            
            if (response.IsSuccessStatusCode)
            {
            	return response;
            }
            
            response.Dispose();
            
            await Task.Delay(TimeSpan.FromSeconds(DelaySeconds));
        }
        
        return response;
    }
}

Instantiate a client from a Lazy constructor


private static Lazy<HttpClient> ApiClient = new(() =>
{
    HttpClientHandler clientHandler = new()
    {
    	SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11
    };
    
    RetryHandler retryHandler = new(clientHandler)
    {
    	DelaySeconds = 5,
        MaxRetries = 3
    };
    
    HttpClient client = new(retryHandler)
    {
    	Timeout = TimeSpan.FromSeconds(60)
    };

    return client;
});

Post a Comment

Previous Post Next Post