gpt4 book ai didi

c# - 如何获取 CookieContainer 的所有 Cookie?

转载 作者:IT王子 更新时间:2023-10-29 04:42:34 50 4
gpt4 key购买 nike

我想使用 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();
}

最佳答案

使用反射的解决方案:

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 发布并引入了提取 CookieCollectionCookieContainer.GetAllCookies() 方法 - Documentation link .

public System.Net.CookieCollection GetAllCookies();

关于c# - 如何获取 CookieContainer 的所有 Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983166/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com