How to ignore SSL validation errors in a HttpClient in C#?
SSL certificates - some days they'll give your end users that false sense of security that only a beautiful green lock icon can bring, and some other days they'll throw you in a world of pain because one randomly expired and hence the API you use to update your certificates is now inaccessible.
For these unfortunate and undesirable situations (and of course local dev, CI jobs, or test services with self‑signed certs) you may need HttpClient to look the other way for a short while - just long enough for you to do whatever you had to with whatever fake ACME certificate you happened to have laying around.
In this article, I'll show a minimal, .NET (Core)‑compatible way to do that.
Background
Note that most of the time this should be thought of as a development/test convenience, not a production pattern. Silently accepting any certificate defeats the whole point of TLS and exposes you to man‑in‑the‑middle attacks.
Prefer adding the cert to the trust store, using a proper CA, or configuring your environment to use a valid certificate. Use the ignore‑validation approach only behind a firewall, with feature flags, or in ephemeral test runs.
Below you'll find a minimal, .NET Core/.NET‑compatible handler-based solution (ServicePointManager tricks are for .NET Framework only), plus the slightly more concise built‑in delegate option. The Background and Solution sections explain why and how it works, and point to safer alternatives.
Solution
I first tried to achieve this with GitHub Copilot, with 2 different comments, and it ended up suggesting me 4 different solutions, each using ServicePointManager - which surely works for .NET Framework, but does NOT work for .NET Core/.NET Standard anymore.
I then proceeded to Google, I mean Bing, ferociously, and very quickly came up with this:
var handler = new HttpClientHandler();
if (SettingsCache.Settings.IgnoreSslErrors)
{
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
}
_httpClient = new HttpClient(handler);
(Also, it works)
Or if you like funny, built-in delegate names, you can also do this instead:
handler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
And there you go.
Comments
No comments yet.