1

I have the below code that I wish to transfer over to a .NET 6 Core.

HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
CookieContainer cookieContainer = new CookieContainer();

// Setup the cookie container
handler.CookieContainer = cookieContainer;

But instead of newing up the HttpClient, I want to use the HttpClientFactory. However, I can't figure how to use the HttpClientFactory with an existing instance of the HttpClientHandler.

I need the instance of the handler, since I use it with the CookieContainer.

I don't care if I use a DI instance of the HttpClientFactory, or if I can create the HttpClient instance directly in my Program.cs.

Any help would be appreciated. Thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Richard
  • 1,054
  • 1
  • 19
  • 36
  • Use DI for this? –  Aug 20 '22 at 14:57
  • But, what is the syntax? I mentioned DI in the question. I have created an HttpClient using builder.Services.AddHttpClient in a Program.cs file many times. However, I don't know how to do this with a HttpClientHandler. Do you have a solution? – Richard Aug 20 '22 at 14:59
  • Does this answer your question? [How to use HttpClientHandler with HttpClientFactory in .NET Core](https://stackoverflow.com/questions/50747749/how-to-use-httpclienthandler-with-httpclientfactory-in-net-core) – Dimitris Maragkos Aug 20 '22 at 15:12
  • @DimitrisMaragkos I saw this answer. However it looks as though it is creating an instance of the HttpClientHander when it creates the HttpClient. How can I get the HttpClientHandler out of the HttpClient to set the CookieContainer? – Richard Aug 20 '22 at 15:17
  • [With reflection you can access it](https://stackoverflow.com/questions/62999782/access-httpclienthandler-from-httpclient-instance) – Peter Csala Sep 28 '22 at 04:49
  • See [Do pooled HttpClient instances keep the CookieContainer?](https://stackoverflow.com/questions/65227400/do-pooled-httpclient-instances-keep-the-cookiecontainer) – hIpPy Nov 30 '22 at 21:50

0 Answers0