Home > OS >  C# accept server certificate using Asp.Net AddHttpClient
C# accept server certificate using Asp.Net AddHttpClient

Time:07-21

I want to request a third party server from my Asp.Net Web-Api and am using AddHttpClient to inject the HttpClient but I´m getting Http-Code 403 Forbidden. Usally I would use the following line to accept the certifiacte:

        var handler = new HttpClientHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            };

        Log.Trace("Create HttpClient");
        using var client = new HttpClient(handler);

But as I use this line I cannot pass a constructor parameter:

        services.AddHttpClient<IMyService, MyService>(client =>
        {
            client.BaseAddress = new System.Uri(_serverURI);
        });

I know .AddHttpClientHandler but this is not working like I want it to. Someone suggest a solution to inject the HttpClientHandler?

CodePudding user response:

You can configure the message handler by chaining the method ConfigurePrimaryHttpMessageHandler microsoft.extensions.dependencyinjection.httpclientbuilderextensions.configureprimaryhttpmessagehandler:

services.AddHttpClient<IMyService, MyService>(client =>
{
     client.BaseAddress = new System.Uri(_serverURI);
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
     return new HttpClientHandler
     {
        ClientCertificateOptions = ClientCertificateOption.Manual,
        ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            }
     };
});
  • Related