Search code examples
c#asp.net-coredotnet-httpclientpollyretry-logic

how to re-try request for 401 along with TransientHttpError ( 5XX and 408)


Below code re-try 2 times when we have error from HttpRequestException, 5XX and 408 and it's works fine.

Here I want to re-try for even 401 error? how we can achieve this with Polly?

 services.AddHttpClient(Options.DefaultName)
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
            .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

Solution

  • Add .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized) to your code:

    services.AddHttpClient(Options.DefaultName)
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
            .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
            .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
    

    I would suggest rewriting your code like this to make it easier to read:

    services.AddHttpClient(Options.DefaultName)
            .AddTransientHttpErrorPolicy(builder => 
                builder
                    .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            );