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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With