C#C
C#3y ago
júlio

❔ CookieContainer and IHttpClientFactory

Hello, I'm currently migrating some old code base (.Net Core 3.0), and the code itself has a bunch of code smells, so I'm trying to improve it a bit (a bunch).
It was a big Web Service and I'm also splitting it into smaller Web Services.
I'm looking to take advantage of the IHtppClientFactory. I understand the concept, it reuses a HttpClient object for the connections, but I have a issue.
The old code did something like this in one of the Controllers:

public class myClass
{
  private HttpClient _client;
  private CookieContainer _cookieContainer;
  private HttpClientHandler _httpClientHandler;

  public myClass() 
  {
    _cookieContainer = new CookieContainer();
    _httpClientHandler= new HttpClientHandler
    {
      AllowAutoRedirect = false,
      CookieContainer = _cookieContainer,
      AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,                
    };

    _client= new HttpClient(_httpClientHandler);
    _client.Timeout = TimeSpan.FromSeconds(30);
    ConfigureDefaultHeaders();
  }
  
  private void ConfigureDefaultHeaders()
  {
    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
  }
  // ...
}
Was this page helpful?