title: How to store cookies using HttpClient in C#?
body: <p>I'm trying to transmit some data from my application to a specific web service using HttpClient. To do that I first have to login to the web service and receive the cookie (that's the authentication method used by the web service). I do it like that:</p>
  
  <pre><code>Uri uri = "login_uri";
  CookieContainer CookieContainer_login = new CookieContainer();
  HttpClientHandler ch = new HttpClientHandler
  {
     AllowAutoRedirect = true,
     CookieContainer = CookieContainer_login,
     UseCookies = true
  };
  HttpClient client = new HttpClient(ch);
  List&lt;KeyValuePair&lt;string, string&gt;&gt; pairs = new List&lt;KeyValuePair&lt;string, string&gt;&gt;
  {
     new KeyValuePair&lt;string, string&gt;("user", "test"),
     new KeyValuePair&lt;string, string&gt;("password", "test"),
     new KeyValuePair&lt;string, string&gt;("loginSource", "0")
  };
  FormUrlEncodedContent content = new FormUrlEncodedContent(pairs);
  System.Threading.Tasks.Task&lt;HttpResponseMessage&gt; response = client.PostAsync(uri, content);
  </code></pre>
  
  <p>It works, I receive the message about successful login via Fiddler. Now in order to use the web service (another Uri), for example to send a POST request, I have to pass my cookies (received during login process) to that request. As I am storing the cookies in the CookieContainer called CookieContainer_login I thought, that I can simply use the same client and only change the Uri in the PostAsync method or create a new client with the same HttpClientHandler and CookieContainer. Unfortunately it didn't work. Actually, I found out, that my CookieContainer is empty, even after the login process. </p>
  
  <p>I tried to recreate that with HttpWebRequest like that:</p>
  
  <pre><code>string url_login = "login_uri";
  string logparam = "user=test&amp;password=test&amp;loginSource=0";
  HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url_login);
  loginRequest.ContentType = "application/x-www-form-urlencoded";
  loginRequest.Accept = "text/xml";
  loginRequest.Method = "POST";
  loginRequest.CookieContainer = CookieContainer_login;
  
  byte[] byteArray = Encoding.UTF8.GetBytes(logparam);
  
  loginRequest.ContentLength = byteArray.Length;
  
  Stream dataStream_login = loginRequest.GetRequestStream();
  dataStream_login.Write(byteArray, 0, byteArray.Length);
  </code></pre>
  
  <p>It works, I also receive the successful login message, but also when I check the CookieContainer count, it shows 3 cookies that are being stored after login. Now my question is why with HttpClient there are no cookies in CookieContainer, but with the HttpWebRequest there are? How to get the cookies with the HttpClient as well?</p>