2011-11-29 5 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

कुकीआई को प्राप्त करने वाले यूआरआई को निर्दिष्ट करते हुए कुकी कोंटेनर की गेटक्यूकी विधि का उपयोग करें। यह एक कुकी कोलेक्शन देता है जिसे आप समझा सकते हैं।

+0

'foreach बयान प्रकार 'System.Net.CookieContainer' के चर पर काम नहीं कर सकते क्योंकि 'System.Net.CookieContainer' के लिए पाश के लिए 'GetEnumerator'' –

+0

उपयोग के बजाय करने के लिए एक सार्वजनिक परिभाषा शामिल नहीं है उन्हे लाओ? –

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