title: Add cookies to dependancy injected HttpClient in Asp.Net Core
body: <p>how can I add cookies to <code>HttpClient</code> used in injected service (<a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests" rel="nofollow noreferrer">example</a>)? I have created some service <code>ApiService</code> and that service has <code>HttpClient</code> injected just like <code>CatalogService</code> in tutorial. Problem is, in order to communicate with external API, my service and it's <code>HttpClient</code> must have a token which was previously received by another API called <code>IdentityService</code> using <code>LoginService</code>. So, when login is completed in fronted web app:</p>
  
  <pre><code>if (!string.IsNullOrEmpty(user.Token)) {
      ClaimsPrincipal principal = ValidateToken(user.Token);
      if (principal != null) {
          AuthenticationProperties p = new AuthenticationProperties();
          p.ExpiresUtc = DateTime.UtcNow.AddDays(7);
          p.IsPersistent = Persistant;
          p.RedirectUri = Request.Query.ContainsKey("ReturnUrl") ? Request.Query["ReturnUrl"].ToString() : "";
  
          await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, p);
  
          // those cookies are lost when ApiController is called - new instance of http client replaces this one
          var apiService = HttpContext.RequestServices.GetService(typeof(IApiService));
          var s = apiService as ApiService;
          s.SetClientCookies("token", user.Token);
  
          return new RedirectToPageResult("../Index");
      }
  }
  
  return BadRequest("Invalid token");
  </code></pre>
  
  <p><code>SetClientCookies</code> currently looks like this but it isn't working because ApiService constructor gets a new instance of HttpClient:</p>
  
  <pre><code>public class ApiService: IApiService {
      public static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
      private HttpClient _client;
      static string BaseUrl = "https://localhost:44365/api";
  
      public ApiService(HttpClient client) {
          _client = client;
      }
  
      public async Task &lt; List &lt; DbTest &gt;&gt; GetAccounts() {
          var httpResponse = await _client.GetAsync(BaseUrl + "/account");
  
          if (!httpResponse.IsSuccessStatusCode) {
              throw new Exception("Cannot retrieve login");
          }
  
          var content = await httpResponse.Content.ReadAsStringAsync();
          var accounts = JsonConvert.DeserializeObject &lt; List &lt; DbTest &gt;&gt; (content);
  
          return accounts;
      }
  
      public void SetClientCookies(string key, string value) {
          _client.DefaultRequestHeaders.Add("Cookie", key + "=" + value);
      }
  }
  </code></pre>
  
  <p>Result is, when API is called with <code>HttpClient</code>, there is no "token" cookie... Any idea how to change this so <code>ApiService</code>'s <code>HttpClient</code> doesn't lose its cookies which are received on login?</p>
  
  <p>Related <code>Startup.cs</code> code is this:</p>
  
  <pre><code>services.AddHttpClient&lt;ILoginService, LoginService&gt;("identityServiceClient");
  
  services.AddHttpClient&lt;IApiService, ApiService&gt;("apiServiceClient")
      .ConfigureHttpClient(client =&gt; {
          client.Timeout = TimeSpan.FromSeconds(30);
      }).ConfigurePrimaryHttpMessageHandler(() =&gt; new HttpClientHandler() {
          CookieContainer = new CookieContainer()
      });
  </code></pre>