感谢 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();