如何获得饼干信息一的CookieContainer里面? (所有的人,不是为特定的域)所有的人、饼干、如何获得、里面

2023-09-09 21:04:46 作者:ポ

请参见下面的code:

Please see the code below:

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 的cookies信息? (所有这些,不只是一个特定的领域。) 我怎么可以添加或删除的cookie?

How can I get cookies info inside cookieJar? (All of them, not just for a specific domain.) And how can I add or remove a cookie from that?

推荐答案

反射可以用来获取私有字段持有的CookieContainer对象中所有域密钥,

reflection can be used to get the private field that holds all the domain key in CookieContainer object,

问。我如何得到该私有字段的名字?

答。使用反射器;

它被声明为:

private Hashtable m_domainTable;

一旦我们得到了私人领域,我们将得到域密钥,然后让饼干是一个简单的迭代。

once we get the private field, we will get the the domain key, then getting cookies is a simple iteration.

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

    }

}