5

Here's the code:

public static async Task<string> DownloadPageWithCookiesAsync(string url) { HttpClientHandler handler = new HttpClientHandler(); handler.UseDefaultCredentials = true; handler.AllowAutoRedirect = true; handler.UseCookies = true; handler.CookieContainer = new CookieContainer(); HttpClient client = new HttpClient(handler); HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); string responseBody = response.Content.ReadAsString(); return responseBody; } 

after the client.GetAsync(url); runs, the handler.CookieContainer contains 7 cookies. How can I access them?

4 Answers 4

3

Use the CookieContainer's GetCookies method, specifying the URI you want cookies for. It returns a CookieCollection you can enumerate.

Sign up to request clarification or add additional context in comments.

4 Comments

foreach statement cannot operate on variables of type 'System.Net.CookieContainer' because 'System.Net.CookieContainer' does not contain a public definition for 'GetEnumerator'
Use for loop instead to get them?
Thanks but Loop on what? There is no index operator defined.
You misunderstood - don't foreach over the CookieContainer. Rather, foreach over the result of the .GetCookies() call. That returns a CookieCollection, which has an iterator.
3

Try:

CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(/*Uri that the cookies are associated with*/)); for(int i = 0; i < cookies.Count; i++) { Cookie c = cookies[i]; //Do stuff with the cookie. } 

You can also iterate the CookieCollection with a foreach loop, I believe.

Comments

2
CookieCollection cookies = handler.CookieContainer.GetCookies(/*blah-blah*/); foreach (var cookie in cookies.OfType<System.Net.Cookie>()) { // process cookies } 

Comments

1
int loop1, loop2; HttpCookieCollection MyCookieColl; HttpCookie MyCookie; MyCookieColl = Request.Cookies; // Capture all cookie names into a string array. String[] arr1 = MyCookieColl.AllKeys; // Grab individual cookie objects by cookie name. for (loop1 = 0; loop1 < arr1.Length; loop1++) { MyCookie = MyCookieColl[arr1[loop1]]; Response.Write("Cookie: " + MyCookie.Name + "<br>"); Response.Write ("Secure:" + MyCookie.Secure + "<br>"); //Grab all values for single cookie into an object array. String[] arr2 = MyCookie.Values.AllKeys; //Loop through cookie Value collection and print all values. for (loop2 = 0; loop2 < arr2.Length; loop2++) { Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.