An extension class of CookieContainer, cookiecontainer
The Cookie returned by the server is frequently used in recent projects. Because HttpClient is used in the project and CookieContainer is used to automatically host the Cookie, it is not convenient to obtain the Cookie. So I wrote an extension class.
First, retrieve all cookies through traversal, store the dictionary into the dictionary, and store the dictionary into the memory cache. When you call the method next time, check whether the dictionary is in the cache. If not, traverse it again. When the number of CookieContainer changes, the value is assigned again.
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> /// add cache /// </summary> /// <param name = "cache"> </param> /// <param name = "key"> </param> /// <param name = "obj"> </param> // <param name = "timeout"> cache expiration time, unit: minute. The default value is 30 minutes. </param> /// <returns> </returns> private stat Ic 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 = AddOrU PdateCache (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) // quantity change, update object {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 );}}