UncleMahler
UncleMahler

Reputation: 101

SSL policy error when using HttpClient (.NET)

I'm trying to utilize a REST API on a local web server with a self-signed certificate. At runtime, the application throws the error

AuthenticationException: The remote certificate is invalid according to the validation procedure.

I have tried the fix in this answer: https://stackoverflow.com/a/1386568/8980983 however the error remains. Code is below:

static void Main(string[] args)
    {
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Clear();

        ServicePointManager.ServerCertificateValidationCallback = delegate (
            object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };
        var loginPage = httpClient.GetAsync("https://<local IP address>/loginpage.html").GetAwaiter().GetResult();

        //do stuff with response...
    }

Any ideas of what I can do to effectively ignore SSL policy errors?

Upvotes: 3

Views: 1776

Answers (1)

UncleMahler
UncleMahler

Reputation: 101

Figured it out. Turns out the HttpClient class doesn't use the ServicePointManager.ServerCertificateValidationCallback method. Solution was as follows:

static void Main(string[] args)
    {
        HttpClientHandler httpClientHandler = new HttpClientHandler();
        httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };

        HttpClient httpClient = new HttpClient(httpClientHandler);
        httpClient.DefaultRequestHeaders.Clear();

        var loginPage = httpClient.GetAsync("https://<local IP address>/loginpage.html").GetAwaiter().GetResult();
     }

Upvotes: 6

Related Questions