请看下面的代码:
CookieContainer cookieJar = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com"); request.CookieContainer = cookieJar; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); int cookieCount = cookieJar.Count;
解决方法
可以使用反射来获取保存CookieContainer对象中所有域密钥的私有字段,
问:我如何获得该私人领域的名称?
答.使用反射器
它被宣布为:
private Hashtable m_domainTable;
一旦我们获得了私人领域,我们将获得域密钥,然后获取Cookie是一个简单的迭代.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Net; using System.Collections; namespace ConsoleApplication4 { static class Program { private static void Main() { CookieContainer cookies = new CookieContainer(); cookies.Add(new Cookie("name1","value1","/","domain1.com")); cookies.Add(new Cookie("name2","value2","domain2.com")); Hashtable table = (Hashtable) cookies.GetType().InvokeMember("m_domainTable",BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance,null,cookies,new object[] { }); foreach (var key in table.Keys) { foreach (Cookie cookie in cookies.GetCookies(new Uri(string.Format("http://{0}/",key)))) { Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",cookie.Name,cookie.Value,cookie.Domain); } } Console.Read(); } } }