28

我想使用 Newtonsoft.Json 将 CookieContainer 导出到 JSON,但不幸的是 CookieContainer 没有枚举器或其他东西,所以我无法循环遍历它......

编辑:使用我发布的解决方案,它将是这样的:

private static void Main(string[] args)
{
    CookieContainer cookieContainer = new CookieContainer();
    cookieContainer.Add(new Cookie("name1", "value1", "/", ".testdomain1.com"));
    cookieContainer.Add(new Cookie("name2", "value1", "/path1/", ".testdomain1.com"));
    cookieContainer.Add(new Cookie("name2", "value1", "/path1/path2/", ".testdomain1.com"));
    cookieContainer.Add(new Cookie("name1", "value1", "/", ".testdomain2.com"));
    cookieContainer.Add(new Cookie("name2", "value1", "/path1/", ".testdomain2.com"));
    cookieContainer.Add(new Cookie("name2", "value1", "/path1/path2/", ".testdomain2.com"));

    CookieCollection cookies = GetAllCookies(cookieContainer);

    Console.WriteLine(JsonConvert.SerializeObject(cookies, Formatting.Indented));
    Console.Read();
}
4

4 回答 4

25

使用反射的解决方案:

public static CookieCollection GetAllCookies(CookieContainer cookieJar)
{
    CookieCollection cookieCollection = new CookieCollection();

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

    foreach (var tableKey in table.Keys)
    {
        String str_tableKey = (string) tableKey;

        if (str_tableKey[0] == '.')
        {
            str_tableKey = str_tableKey.Substring(1);
        }

        SortedList list = (SortedList) table[tableKey].GetType().InvokeMember("m_list",
                                                                    BindingFlags.NonPublic |
                                                                    BindingFlags.GetField |
                                                                    BindingFlags.Instance,
                                                                    null,
                                                                    table[tableKey],
                                                                    new object[] { });

        foreach (var listKey in list.Keys)
        {
            String url = "https://" + str_tableKey + (string) listKey;
            cookieCollection.Add(cookieJar.GetCookies(new Uri(url)));
        }
    }

    return cookieCollection;
}

.NET 6 更新

最后,.NET 6 发布并引入了CookieContainer.GetAllCookies()提取CookieCollection-文档链接的方法。

public System.Net.CookieCollection GetAllCookies();
于 2013-04-13T18:01:03.017 回答
15

无论协议是什么,此方法都将确保获取所有 cookie:

public static IEnumerable<Cookie> GetAllCookies(this CookieContainer c)
{
    Hashtable k = (Hashtable)c.GetType().GetField("m_domainTable", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(c);
    foreach (DictionaryEntry element in k)
    {
        SortedList l = (SortedList)element.Value.GetType().GetField("m_list", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(element.Value);
        foreach (var e in l)
        {
            var cl = (CookieCollection)((DictionaryEntry)e).Value;
            foreach (Cookie fc in cl)
            {
                yield return fc;
            }
        }
    }
}
于 2015-08-09T03:42:46.257 回答
9

第一个答案不适用于便携式项目。所以这里的选项2,也使用反射

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

    public static CookieCollection GetAllCookies(this CookieContainer container)
    {
        var allCookies = new CookieCollection();
        var domainTableField = container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable");            
        var domains = (IDictionary)domainTableField.GetValue(container);

        foreach (var val in domains.Values)
        {
            var type = val.GetType().GetRuntimeFields().First(x => x.Name == "m_list");
            var values = (IDictionary)type.GetValue(val);
            foreach (CookieCollection cookies in values.Values)
            {
                allCookies.Add(cookies);                    
            }
        }          
        return allCookies;
    }

1)我也试过

var domainTableField = container.GetType().GetRuntimeField("m_domainTable"); 

但它返回空值。

2)您可以遍历 domain.Keys 并对所有键使用 container.GetCookies() 。但是我遇到了问题,因为 GetCookies 需要 Uri 而不是我所有的键都匹配 Uri 模式。

于 2015-05-06T15:10:38.290 回答
-3

使用CookieContainer.GetCookies 方法

CookieCollection cookies = cookieContainer.GetCookies(new Uri(url));

url您网站的网址在哪里。

就我而言,正如其他答案中所建议的那样,我无法使用反射。但是,我确实知道要查询的网站的 URL。我认为容器不会盲目地返回所有 cookie 而是按 URL 返回它们甚至是合乎逻辑的,因为 cookie 始终属于特定的 URL,并且不能在与它们关联的域的上下文之外使用。

于 2018-01-25T14:12:39.483 回答