title: C# How to pass on a cookie using a shared HttpClient
body: <p>I have the following set up:</p>
  
  <p>JS client -> Web Api -> Web Api</p>
  
  <p>I need to send the auth cookie all the way down. My problem is sending it from one web api to another. Because of integration with an older system, that uses FormsAuthentication, I have to pass on the auth cookie.</p>
  
  <p>For performance reasons I share a list of HttpClients (one for each web api) in the following dictionary:</p>
  
  <pre><code>private static ConcurrentDictionary&lt;ApiIdentifier, HttpClient&gt; _clients = new ConcurrentDictionary&lt;ApiIdentifier, HttpClient&gt;();
  </code></pre>
  
  <p>So given an identifier I can grab the corresponding HttpClient.</p>
  
  <p>The following works, but I'm pretty sure this is bad code:</p>
  
  <pre><code>HttpClient client = _clients[identifier];
  var callerRequest = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
  string authCookieValue = GetAuthCookieValue(callerRequest);
  
  if (authCookieValue != null)
  {
      client.DefaultRequestHeaders.Remove("Cookie");
      client.DefaultRequestHeaders.Add("Cookie", ".ASPXAUTH=" + authCookieValue);
  }
  
  HttpResponseMessage response = await client.PutAsJsonAsync(methodName, dataToSend);
  
  // Handle response...
  </code></pre>
  
  <p>Whats wrong about this is that 1) it seems wrong to manipulate <code>DefaultRequestHeaders</code> in a request and 2) potentially two simultanious requests may mess up the cookies, as the HttpClient is shared.</p>
  
  <p>I've been searching for a while without finding a solution, as most having a matching problem instantiates the HttpClient for every request, hence being able to set the required headers, which I'm trying to avoid.</p>
  
  <p>At one point I had get requests working using a <code>HttpResponseMessage</code>. Perhaps that can be of inspiration to a solution.</p>
  
  <p>So my question is: is there a way to set cookies for a single request using a HttpClient, that will be safe from other clients using the same instance?</p>