1

Recently read about how httpclient should be reused and not disposed. In the original implementation, we instantiate httpclient every time it is used which opens many tcp connections unnecessarily. Different parts of the app using httpclient call different endpoints and some even use certificates.

Having trouble on how to architect its usage in an MVC application. Using a static httpclient per controller in a static constructor seemed like a good idea, but some usage is with a webrequesthandler that adds a client certificate. How do I go about handling replacement certificates without having to restart the app pool?

    private static readonly HttpClient _httpClient;

    static MyController()
    {
        var clientHandler = new WebRequestHandler();
        var certPath = HostingEnvironment.MapPath("~/Certificates");
        string[] files = Directory.GetFiles(certPath, "*.pfx");

        foreach (var file in files)
        {
            clientHandler.ClientCertificates.Add(GetClientCertificate(file));
        }

        _httpClient = new HttpClient(clientHandler);
    }
asunrey
  • 875
  • 2
  • 10
  • 28
  • 1
    You could create a singleton class that contains a static httpClient. Reuse your singleton everywhere you would normally use the HttpClient. Write custom methods inside that singleton class that refreshes the inner httpclient with a new client certificate – maccettura Jan 09 '18 at 22:09
  • 1
    **Hi** try this**strong text** [Httpclient With Certs](https://stackoverflow.com/questions/39294983/httpclient-reused-with-client-certificate) – ayoubzghondi Jan 09 '18 at 22:38
  • 1
    Apparently you can continue to use the WebRequestHandler which contains methods for clearing the certificate. HttpClient continues to hold its reference to the handler. – asunrey Jan 11 '18 at 05:08
  • 1
    Does this answer your question? [Re-set the certificate of singleton httpclient (Reconfiguring IHttpclientFactory?)](https://stackoverflow.com/questions/63375951/re-set-the-certificate-of-singleton-httpclient-reconfiguring-ihttpclientfactory) – Marius Stănescu Jun 28 '23 at 09:22

0 Answers0