18

请看下面的代码:

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;

我怎样才能得到里面的cookies信息cookieJar?(所有这些,不只是针对特定域。)
我如何添加或删除 cookie?

4

6 回答 6

17

没有一个答案对我有用。这是我对这个问题的谦虚解决方案。

public static List<Cookie> List(this CookieContainer container)
{
    var cookies = new List<Cookie>();

    var table = (Hashtable)container.GetType().InvokeMember("m_domainTable",
        BindingFlags.NonPublic |
        BindingFlags.GetField |
        BindingFlags.Instance,
        null,
        container,
        null);

    foreach (string key in table.Keys)
    {
        var item = table[key];
        var items = (ICollection) item.GetType().GetProperty("Values").GetGetMethod().Invoke(item, null);
        foreach (CookieCollection cc in items)
        {
            foreach (Cookie cookie in cc)
            {
                cookies.Add(cookie);
            }
        }
    }

    return cookies;
}           
于 2018-05-27T03:02:42.373 回答
16

反射可用于获取包含 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)
            {
                Uri uri = new Uri(string.Format("http://{0}/", key));

                foreach (Cookie cookie in cookies.GetCookies(uri))
                {
                    Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",
                        cookie.Name, cookie.Value, cookie.Domain);
                }
            }

            Console.Read();
        }
    }
}
于 2012-12-28T18:42:45.950 回答
7

感谢 AppDeveloper 的回答,这里有一个稍微修改过的版本作为扩展方法。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

public static class CookieContainerExtension
{
    public static List<Cookie> List(this CookieContainer container)
    {
        var cookies = new List<Cookie>();

        var table = (Hashtable)container.GetType().InvokeMember("m_domainTable",
                                                                BindingFlags.NonPublic |
                                                                BindingFlags.GetField |
                                                                BindingFlags.Instance,
                                                                null,
                                                                container,
                                                                new object[] { });

        foreach (var key in table.Keys)
        {

            Uri uri = null;

            var domain = key as string;

            if (domain == null)
                continue;

            if (domain.StartsWith("."))
                domain = domain.Substring(1);

            var address = string.Format("http://{0}/", domain);

            if (Uri.TryCreate(address, UriKind.RelativeOrAbsolute, out uri) == false)
                continue;

            foreach (Cookie cookie in container.GetCookies(uri))
            {
                cookies.Add(cookie);
            }
        }

        return cookies;
    }
}

要获取列表,只需在 CookieContainer 上调用 List():

CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("name1", "value1", "/", "www.domain1.com"));
cookies.Add(new Cookie("name2", "value2", "/", "www.domain2.com"));
List<Cookie> cookieList = cookies.List();
于 2014-07-01T13:59:30.120 回答
5

PaRiMal RaJ 代码的改进版本。此方法将同时打印 http 和 https cookie。准备将其粘贴到您的班级中。

    // Paste this dependencies in your class
    using System;
    using System.Net;
    using System.Linq;
    using System.Reflection;
    using System.Collections;
    using System.Collections.Generic;

    /// <summary>
    /// It prints all cookies in a CookieContainer. Only for testing.
    /// </summary>
    /// <param name="cookieJar">A cookie container</param>
    public void PrintCookies (CookieContainer cookieJar)
    {
        try
        {
            Hashtable table = (Hashtable) cookieJar
                .GetType().InvokeMember("m_domainTable",
                BindingFlags.NonPublic |
                BindingFlags.GetField |
                BindingFlags.Instance,
                null,
                cookieJar,
                new object[] {});


            foreach (var key in table.Keys)
            {
                // Look for http cookies.
                if (cookieJar.GetCookies(
                    new Uri(string.Format("http://{0}/", key))).Count > 0)
                {
                    Console.WriteLine(cookieJar.Count+" HTTP COOKIES FOUND:");
                    Console.WriteLine("----------------------------------");
                    foreach (Cookie cookie in cookieJar.GetCookies(
                        new Uri(string.Format("http://{0}/", key))))
                    {
                        Console.WriteLine(
                            "Name = {0} ; Value = {1} ; Domain = {2}", 
                            cookie.Name, cookie.Value,cookie.Domain);
                    }
                }

                // Look for https cookies
                if (cookieJar.GetCookies(
                    new Uri(string.Format("https://{0}/", key))).Count > 0)
                {
                    Console.WriteLine(cookieJar.Count+" HTTPS COOKIES FOUND:");
                    Console.WriteLine("----------------------------------");
                    foreach (Cookie cookie in cookieJar.GetCookies(
                        new Uri(string.Format("https://{0}/", key))))
                    {
                        Console.WriteLine(
                            "Name = {0} ; Value = {1} ; Domain = {2}", 
                            cookie.Name, cookie.Value,cookie.Domain);
                    }
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine (e);
        }
    }
于 2016-04-16T15:06:00.797 回答
3

这是一个扩展,它结合了 antfx 的代码和 Adrian Lopez 的同时使用 http 和 https 的想法。对于任何可能觉得它有用的人来说,这只是一个快速修复:

public static class CookieContainerExtensions
{
    public static List<Cookie> List(this CookieContainer container)
    {
        var cookies = new List<Cookie>();

        var table = (Hashtable)container.GetType().InvokeMember("m_domainTable",
                                                                BindingFlags.NonPublic |
                                                                BindingFlags.GetField |
                                                                BindingFlags.Instance,
                                                                null,
                                                                container,
                                                                new object[] { });

        foreach (var key in table.Keys)
        {
            var domain = key as string;

            if (domain == null)
                continue;

            if (domain.StartsWith("."))
                domain = domain.Substring(1);

            var httpAddress = string.Format("http://{0}/", domain);
            var httpsAddress = string.Format("https://{0}/", domain);

            if (Uri.TryCreate(httpAddress, UriKind.RelativeOrAbsolute, out var httpUri))
            {
                foreach (Cookie cookie in container.GetCookies(httpUri))
                {
                    cookies.Add(cookie);
                }
            }
            if (Uri.TryCreate(httpsAddress, UriKind.RelativeOrAbsolute, out var httpsUri))
            {
                foreach (Cookie cookie in container.GetCookies(httpsUri))
                {
                    cookies.Add(cookie);
                }
            }
        }

        return cookies;
    }
}
于 2018-04-26T20:14:38.580 回答
1

如果你要编写一个 nUnit 测试,它会是这样的:

    [Test]
    public void Test()
    {

        CookieContainer cookies = new CookieContainer();
        cookies.Add(new Cookie("name1", "value1", "/", "www.domain1.com"));
        cookies.Add(new Cookie("name2", "value2", "/", "www.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.ToString().Substring(1,key.ToString().Length - 1)))))
            {
                Assert.That(cookie != null);
                //Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}", cookie.Name, cookie.Value,
                //                  cookie.Domain);
            }
        }



    }
于 2013-12-23T18:49:25.543 回答