dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.42k stars 4.76k forks source link

Allow to Specify HttpClientHandler in IHttpClientFactory #110009

Open rdethurenssftcom opened 1 day ago

rdethurenssftcom commented 1 day ago

Background and Motivation

We currently use IHttpClientFactory via dependency injection to generate our HttpClient. In some of our use cases, we need to define ClientCertificates to connect to the target server. This can only be done by the HttpClientHandler. However, we can only set the right certificate within the scope of the request. So we can't use the HttpClientHandler configured via the DI. We can create it directly using the HttpClient constructor, but in this case, we lose the configuration performed by the IHttpClientFactory.

We therefore need to dynamically define a handler for an httpClient generated when using an IHttpClientFactory.

Proposed API

namespace System.Net.Http;

public interface IHttpClientFactory
{
  // Existing method
  HttpClient CreateClient(string name);

  // New method
  HttpClient CreateClient(HttpClientHandler handler);
}

Usage Examples

You can use code blocks like this:

            X509Certificate2 certificate = GetCertificateByName(certificateName);
            HttpClientHandler handler = new HttpClientHandler();
            handler.ClientCertificates.Add(certificate);
            HttpClient httpClient = httpClientFactory.CreateClient(handler);

Alternative Designs

We are open to other way to go

Risks

As it add a new method endpoint, the risk of regression is minor

dotnet-policy-service[bot] commented 1 day ago

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.

julealgon commented 1 day ago

Probably a duplicate of, conceptually:

Discussions here might be relevant and provide workarounds:

DL444 commented 1 day ago

IMHO allowing configuration of HttpMessageHandler per-client seems to defeat the purpose of IHttpClientFactory which is to allow the primary handlers to be pooled and shared. Unfortunately as far as I see ClientCertificates seems to be configurable only via HttpClientHandler.