C# · 12月 28, 2021

c# – 如何在CookieContainer中获取Cookie信息? (所有他们,不是一个特定的领域)

请看下面的代码: 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;

如何在CookieJar中获取Cookie信息? (所有这些,不只是一个特定的领域.)
如何添加或删除一个cookie?

解决方法 可以使用反射来获取保存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(); } }}