Search code examples
c#sslasp.net-core.net-coressl-certificate

How to allow all https regardless of validity in .NET Core HttpClient?


I am creating a web API in .NET Core. To debug it locally, I have created a console application that connects to my API. I am debugging in Linux.

When connecting to my local URL at https://localhost:5001/, my console application is throwing an AuthenticationException (The remote certificate is invalid according to the validation procedure).

I have tried to circumvent this in two ways:

  1. Have added ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; but it has no effect.

  2. I have run dotnet dev-certs https --trust. Now my web browser doesn't complain anymore, which is nice, but my console application is still throwing the exception. Have tried rebooting.

How can I make .NET Core trust my localhost server? Or ignore the certificate validity?


Solution

  • Use the sample below from here

    var httpClientHandler = new HttpClientHandler();
    // Return `true` to allow certificates that are untrusted/invalid
    httpClientHandler.ServerCertificateCustomValidationCallback = 
        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
    var httpClient = new HttpClient(httpClientHandler);