最近項目中需要頻繁用到伺服器返回的Cookie,由於項目採用的是HttpClient,並且用CookieContainer自動托管Cookie,在獲取Cookie的時候不太方便。所以就寫了個拓展類。 首先的遍歷獲取所有的Cookie,然後存入字典當中,再把字典存入記憶體緩存中,在下次調用方法的時候,先 ...
最近項目中需要頻繁用到伺服器返回的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=30) { 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); } }