最近项目中需要频繁用到服务器返回的Cookie,由于项目采用的是HttpClient,并且用CookieContainer自动托管Cookie,在获取Cookie的时候不太方便。所以就写了个拓展类。

  首先的遍历获取所有的Cookie,然后存入字典当中,再把字典存入内存缓存中,在下次调用方法的时候,先判断缓存中有没有,没有的话再次遍历出来。当CookieContainer的数量改变后也会重新赋值

  

  

    public static class CookieParser
{
public static ObjectCache Cache = MemoryCache.Default; private static T Get<T>(this ObjectCache cache,string key)
{
return (T)cache.Get(key);
} /// <summary>
/// 增加缓存
/// </summary>
/// <param name="cache"></param>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="timeout">缓存过期时间,单位分钟,默认30分钟</param>
/// <returns></returns>
private static bool Add(this ObjectCache cache,string key, object obj, int timeout=)
{
return Cache.Add(key, obj, DateTime.Now+TimeSpan.FromMinutes(timeout));
} private static readonly object Lock = new object(); public static string GetCookieValue(this CookieContainer cc,string name)
{
return cc.GetCookie(name).Value;
} public static Cookie GetCookie(this CookieContainer cc, string name)
{
var key = AddOrUpdateCache(cc);
return Cache.Get<Dictionary<string, Cookie>>(key)[name];
} public static List<Cookie> GetAllCookie(this CookieContainer cc)
{
var key = AddOrUpdateCache(cc);
return Cache.Get<Dictionary<string, Cookie>>(key).Values.ToList();
} private static string AddOrUpdateCache(CookieContainer cc)
{
var key = cc.GetHashCode().ToString();
lock (Lock)
{
if (!Cache.Contains(key))
{
Cache.Add(key, cc.Parser());
}
else if(Cache.Get<Dictionary<string,Cookie>>(key).Count!=cc.Count)//数量改变,更新对象
{
Cache[key] = cc.Parser();
}
}
return key;
} private static Dictionary<string, Cookie> Parser(this CookieContainer cc)
{
var table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance, null, cc, new object[] { }); return (
from object pathList
in table.Values
select (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { }) into lstCookieCol
from CookieCollection colCookies in lstCookieCol.Values
from Cookie c in colCookies
select c)
.ToDictionary(c => c.Name, c => c);
}
}
05-11 02:42