2011-11-29 69 views
5

下面的代碼:我怎樣才能從餅乾HttpClientHandler.CookieContainer

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; 
} 

client.GetAsync(url);運行後,handler.CookieContainer包含7塊餅乾。我如何訪問它們?

回答

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>"); 
    } 
} 
3

使用CookieContainer的GetCookies方法,指定您想要Cookie的URI。它返回一個你可以枚舉的CookieCollection。

+0

'foreach語句無法在類型「System.Net.CookieContainer」的變量操作,因爲「System.Net.CookieContainer」不包含「GetEnumerator'' –

+0

使用for循環而不是一個公共定義抓住他們? –

+0

感謝但循環在什麼?沒有定義索引運算符。 –

2

嘗試:

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. 
} 

你也可以用foreach循環迭代CookieCollection,我相信。

+0

美觀大方 – baaroz

+0

就是這樣!!!!! –

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