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.

1HttpClient httpClient = new HttpClient();
2var retryPolicy = Policy.Handle<HttpRequestException>().RetryAsync(3, onRetry: (ex, count) => 
3{
4    var httpClientHandler = new HttpClientHandler();
5    httpClientHandler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, sslErrors) => { return true; };
6    httpClient = new HttpClient(httpClientHandler);
7});
8
9var content = await retryPolicy.ExecuteAsync(() => httpClient.GetStreamAsync("https://api.openbrewerydb.org/breweries?by_city=boston"));

That’s it. Love Polly!

comments powered by Disqus

Related