5

According to the best practice, you are supposed to instantiate a single instance of HttpClient and reuse it throughtout your application lifecycle.

But how do you do this when you need to inject a custom HttpClientHandler for every request? (i.e I need to load a custom certificate based on who is calling)

    var clientHandler = new HttpClientHandler();
    clientHandler.ClientCertificates.Add(customCertificate);

    using (var httpClient = new HttpClient(clientHandler))
    {
        // Call another endpoint
    }

Is there any advantage is to creating multiple singleton instances of HttpClient for every use case?

os blue
  • 93
  • 6
  • Can you add all custom certificates to a single instance of `HttpClientHandler`? – Leonid Vasilev Jan 18 '18 at 11:49
  • How many different certs do you have? It is OK to have several HttpClients, but you just don't want too many. Too many being based on several factors. If you dont' have too many use a client per cert. – Crowcoder Jan 18 '18 at 11:58
  • @Crowcoder There could be upto 20, and that could grow. – os blue Jan 18 '18 at 15:22
  • @LeonidVasilyev But if you do that, you cannot control which cert will be used on the request can you? – os blue Jan 18 '18 at 15:22
  • 20 isn't bad unless you have other services on the machine also using a lot of TCP connections. There are also many settings on the client and the ServicePointManager that you can tweak to optimize things but it might take some benchmarking to find your sweet spot. – Crowcoder Jan 18 '18 at 15:29
  • Can [ClientCertificateOption.Automatic](https://msdn.microsoft.com/en-us/library/system.net.http.clientcertificateoption(v=vs.118).aspx) work for you? It looks like certificates have to be in certificate store anyway or you have to override certificate validation. [Force HttpClient to trust single Certificate](https://stackoverflow.com/questions/24221974/force-httpclient-to-trust-single-certificate/24224526) discussion and [Certificate Selection and Validation](https://docs.microsoft.com/en-us/dotnet/framework/network-programming/certificate-selection-and-validation) article are relevant. – Leonid Vasilev Jan 18 '18 at 17:30
  • @osblue how did you solve your issue? – Hooch Jan 18 '22 at 11:48

0 Answers0