title: HttpClient with two handlers
body: <p>I have a server with multiple ip addresses. I want (1) to be able to make requests from all of that addresses and (2) automatically decompress responses. Here is what I came up with:</p>
  <pre><code>foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  {
      if (ip.AddressFamily != AddressFamily.InterNetwork) continue;
                                
      SocketsHttpHandler socketHandler = new();
      socketHandler.ConnectCallback = async (context, cancellationToken) =&gt;
      {
          Socket socket = new(SocketType.Stream, ProtocolType.Tcp);
          socket.Bind(new IPEndPoint(ip, 0));
          socket.NoDelay = true;
          try
          {
              await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false);
              return new NetworkStream(socket, true);
          }
          catch
          {
              socket.Dispose();
              throw;
          }
      };
  
      HttpClientHandler certHandler = new();
      certHandler.AutomaticDecompression = DecompressionMethods.All;
  
      //the problem is below. How to put two handlers into HttpClient?
      HttpChainHandler handlers = new(socketHandler);
      handlers.InnerHandler = certHandler;
      clientsPool.Add(new HttpClient(handlers)); 
  }
  </code></pre>
  <p>where HttpChainHandler is</p>
  <pre><code>public class HttpChainHandler : DelegatingHandler
  {
      public HttpChainHandler(HttpMessageHandler handler) : base(handler)
      {
  
      }
  }
  </code></pre>
  <p>This code doesn't work. I run a test app to <a href="https://api.myip.com" rel="nofollow noreferrer">https://api.myip.com</a> and this site should return my ip address. All addresses are the same so my program make requests from a single ip-address.</p>
  <p>However if I swap socketHandler with certHandler like this:</p>
  <pre><code>HttpChainHandler handlers = new(certHandler); //certHandler here instead of socketHandler
  handlers.InnerHandler = socketHandler; //socketHandler here instead of certHandler
  clientsPool.Add(new HttpClient(handlers)); 
  </code></pre>
  <p>then my requests are made from different ip. Finally! But... automatic decompression doesn't work! If I add headers to client DefaultRequestHeaders.Add(&quot;Accept-Encoding&quot;, &quot;gzip, deflate, br&quot;); then
  <a href="https://api.myip.com" rel="nofollow noreferrer">https://api.myip.com</a> starts to answer with compressed responses.</p>
  <p>So I can't have both socketHandler and certHandler in my HttpClient. In my attempt to combine them with DelegatingHandler whatever I put into its constructor doesn't work.</p>
  <p>UPD:
  I found a source code for DelegatingHandler. Everything you put into its constructor will be assigned to the property InnerHandler so it explains why my attempt to combine two handlers failed. Clearly I'm doing it wrong. The question remains: How to use two handlers with HttpClient?</p>