most recent 30 from stackoverflow.com2026-05-01T14:25:20Zhttps://stackoverflow.com/feeds/question/62860290https://creativecommons.org/licenses/by-sa/4.0/rdfhttps://stackoverflow.com/q/628602902janwhttps://stackoverflow.com/users/85280142020-07-12T11:07:46Z2020-07-24T16:32:12Z
<p>In Startup.cs I inject an <code>IHttpClientFactory</code> service:</p>
<pre><code>services.AddHttpClient();
</code></pre>
<p>I can then create a new <code>HttpClient</code> through</p>
<pre><code>public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
_httpClient = httpClientFactory.CreateClient();
// ...
}
</code></pre>
<p><code>MyClass</code> does some API access; the base URL is passed in the <code>options</code> object.</p>
<p>For testing I set up a dummy instance of the API, which uses a self-signed SSL certificate. Unfortunately, this certificate is (correctly) recognized as invalid:</p>
<pre><code>System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
</code></pre>
<p>How can I disable certificate verification at the factory layer, i.e. directly in the <code>ConfigureServices</code> method?</p>
<p>I found <a href="https://stackoverflow.com/questions/57283898/ignore-ssl-connection-errors-via-ihttpclientfactory">this question</a>, but it seemed to use some custom <code>HttpClient</code> implementation (?), while I want to target the default one. The following does not work (DI picks the wrong constructor and subsequently fails):</p>
<pre><code>services.AddHttpClient<IMyClass, MyClass>();
</code></pre>
<p><a href="https://stackoverflow.com/a/55496011/8528014">This answer</a> suggests to supply a name for the configured <code>HttpClient</code>, but it passes some magic string, which I would like to avoid (<code>MyClass</code> is located in a class library designed to be also used by others). Passing no name does not work either, since <code>AddHttpClient</code> then merely returns an <code>IServiceCollection</code> object.</p>
https://stackoverflow.com/questions/62860290/-/62899563#6289956313janwhttps://stackoverflow.com/users/85280142020-07-14T16:20:34Z2020-07-24T16:32:12Z<p>I figured it out now. We can apply <a href="https://stackoverflow.com/a/57235906/8528014">this answer</a> to modify the primary <code>HttpMessageHandler</code> of the default <code>HttpClient</code>:</p>
<pre><code>services.AddHttpClient(Options.DefaultName, c =>
{
// ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, certChain, policyErrors) => true
};
});
</code></pre>
<p>This will yield <code>HttpClient</code> objects with disabled SSL verification, whenever the default <code>IHttpClientFactory</code> is injected.</p>