This question has been asked a few times before, but I could not find a definite answer. Is it even possible to get response cookies using System.Net.Http.HttpClient?
- Have you looked in the CookieContainer as described by this question stackoverflow.com/questions/17983992/… ?Darrel Miller– Darrel Miller2015-07-04 20:25:31 +00:00Commented Jul 4, 2015 at 20:25
- Yes, I have, as well as a few other posts. None of them show how to get cookies from the response.Alex I– Alex I2015-07-09 19:19:34 +00:00Commented Jul 9, 2015 at 19:19
2 Answers
Below is some sample code I have used for accessing server generated cookies. I just tested it and it worked for me. I changed the credentials though. If you want to see it working you will need to create yourself a nerddinner account.
[Fact] public async Task Accessing_resource_secured_by_cookie() { var handler = new HttpClientHandler(); var httpClient = new HttpClient(handler); Assert.Equal(0, handler.CookieContainer.Count); // Create a login form var body = new Dictionary<string, string>() { {"UserName", "<username>"}, {"Password", "<password>"}, {"RememberMe", "false"} }; var content = new FormUrlEncodedContent(body); // POST to login form var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content); // Check the cookies created by server Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(1, handler.CookieContainer.Count); var cookies = handler.CookieContainer.GetCookies(new Uri("http://www.nerddinner.com")); Assert.Equal(".ASPXAUTH", cookies[0].Name); // Make new request to secured resource var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My"); var stringContent = await myresponse.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, myresponse.StatusCode); } As you can see from the code, you don't get response cookies directly from the HTTP Response message. I suspect the HttpClientHandler strips the header off the response before returning it. However, the cookies from the response are placed in the CookieContainer and you can access them from there.
2 Comments
to get a response cookie you can use this method;
private async Task<string> GetCookieValue(string url, string cookieName) { var cookieContainer = new CookieContainer(); var uri = new Uri(url); using (var httpClientHandler = new HttpClientHandler { CookieContainer = cookieContainer }) { using (var httpClient = new HttpClient(httpClientHandler)) { await httpClient.GetAsync(uri); var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName); return cookie?.Value; } } }