I am working on a project that needs to connect to an https site. Every time I connect, my code throws exception because the certificate of that site comes from untrusted site. Is there a way to bypass certificate check in .net core http?
I saw this code from previous version of .NET. I guess I just need something like this.
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Start Visual Studio 2019 and select Create a new project. In the Create a new project dialog, select ASP.NET Web Application (. NET Framework) > Next. In the Configure your new project dialog, enter SSLSample for Project name.
Update:
As mentioned below, not all implementations support this callback (i.e. platforms like iOS). In this case, as the docs say, you can set the validator explicitly:
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
This works too for .NET Core 2.2, 3.0 and 3.1
Old answer, with more control but may throw PlatformNotSupportedException
:
You can override SSL cert check on a HTTP call with the a anonymous callback function like this
using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; using (var client = new HttpClient(httpClientHandler)) { // Make your request... } }
Additionally, I suggest to use a factory pattern for HttpClient
because it is a shared object that might no be disposed immediately and therefore connections will stay open.
I solve with this:
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return true; } });
YourService.cs
public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings) { _appSettings = appSettings.Value; _clientFactory = clientFactory; } var request = new HttpRequestMessage(... var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted"); HttpResponseMessage response = await client.SendAsync(request);
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