Let's Encrypt Cert Error and Polly Retry

This is very much a temporary workaround, it circumvents normal checks on a certificate. You should only do it if you understand the consequences!

You might have seen discussions around Let’s Encrypts root cert expiring and causing all sorts of problems.

I hit one of them myself, I have an application that calls out to the Open Brewery DB using HttpClient and it started to get HttpRequestExceptions.

Fortunately there is Polly!! It can retry requests that fail, but change how the request is made before it is retried.

With Polly I can make a regular request, it fails because of the cert issue. Then I retry, and force HttpClient to ignore the cert issue by adding a HttpClientHandler to the HttpClient.

1
2
3
4
5
6
7
8
9
HttpClient httpClient = new HttpClient();
var retryPolicy = Policy.Handle<HttpRequestException>().RetryAsync(3, onRetry: (ex, count) => 
{
    var httpClientHandler = new HttpClientHandler();
    httpClientHandler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, sslErrors) => { return true; };
    httpClient = new HttpClient(httpClientHandler);
});

var content = await retryPolicy.ExecuteAsync(() => httpClient.GetStreamAsync("https://api.openbrewerydb.org/breweries?by_city=boston"));

That’s it. Love Polly!

comments powered by Disqus

Related