简体   繁体   中英

How to retrieve Cookies from HttpResponseMessage

I am sending form data in a post request which I know returns cookies but my cookie variable is being returned as empty

I've tried using GetCookies as you can see but I'm wondering if I can filter the cookies out of my PostAsync Response as I get a 200 response

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient client = new HttpClient(handler);
HttpContent content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(targetURI.AbsoluteUri , content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

I expect 2 cookies to come back and be stored in my responseCookies Container

There are some unclear aspects in your question: where does your cookies variable come from, and where does your handler variable come from? These details are important to answer the question.

I can think of 2 possible wrong parts of your code. First, you should attach a CookieContainer to your handler:

var cookies = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookies };
var client = new HttpClient(handler);
var content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
var response = await client.PostAsync(targetURI.AbsoluteUri, content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

Secondly (assuming your cookies and handler variables were initialized that way), you might need to fetch cookies for the correct base address ( Uri.Host ):

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()

If you are completely unsure, please check with this approach (deep inspection based on reflection) if cookies are set at all, and for which domain they are set.

Just so you guys know, the problem was I hadn't encoded my form data. Changed content to the line below.

var content = new FormUrlEncodedContent(formVals);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM