2014-05-16 53 views
1

我正在使用此答案提供的代碼下載並與網站進行交互。讀取cookie感知的WebClient中的cookie的值

https://stackoverflow.com/a/1031335/1689144

// establish the client and base 
CookieAwareWebClient client = new CookieAwareWebClient(); 
client.BaseAddress = @"some_url"; 

// establish login data 
var loginData = new NameValueCollection(); 
loginData.Add("username", Settings.Default.username.ToLower()); 
loginData.Add("password", Settings.Default.password); 

// begin login 
client.UploadValues("/login", "POST", loginData); 

這裏就是我有麻煩。我認爲CookieContainerNameValueCollection。這不是......我如何閱讀CookieContainer的內容?

//NOM NOM NOM cookies 
var nomNomCookies = client.CookieContainer; 
foreach (var cookie in nomNomCookies) 
{ 
    //test 
    Console.WriteLine(cookie.Name + " " + cookie.Value); 
} 

回答

1

如果要使用此解決方案哈克:

public static IEnumerable<Cookie> GetAllCookies(CookieContainer cookieContainer) 
{ 
    var domainTable = (Hashtable)cookieContainer 
          .GetType() 
          .InvokeMember(
           name: "m_domainTable", 
           invokeAttr: BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, 
           binder: null, 
           target: cookieContainer, 
           args: new object[] { }); 

    return domainTable.Keys.Cast<string>() 
       .Select(d => cookieContainer.GetCookies(new Uri("http://" + d.TrimStart('.')))) 
       .SelectMany(c => c.Cast<Cookie>()); 

}