How can I get all Cookies of a CookieContainer?

前端 未结 4 1402
挽巷
挽巷 2020-11-30 09:41

I want to export a CookieContainer to JSON using Newtonsoft.Json but unfortunately CookieContainer hasn\'t an enumerator or stuff, so I can\'t cycle through it ...

<

4条回答
  •  野性不改
    2020-11-30 10:30

    The first answer did not work for a portable project. So here's option 2, also uses reflection

    using System.Linq;
    using System.Collections;
    using System.Reflection;
    using System.Net;
    
        public static CookieCollection GetAllCookies(this CookieContainer container)
        {
            var allCookies = new CookieCollection();
            var domainTableField = container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable");            
            var domains = (IDictionary)domainTableField.GetValue(container);
    
            foreach (var val in domains.Values)
            {
                var type = val.GetType().GetRuntimeFields().First(x => x.Name == "m_list");
                var values = (IDictionary)type.GetValue(val);
                foreach (CookieCollection cookies in values.Values)
                {
                    allCookies.Add(cookies);                    
                }
            }          
            return allCookies;
        }
    

    1) I also tried

    var domainTableField = container.GetType().GetRuntimeField("m_domainTable"); 
    

    but it returned null.

    2) You can iterate through domains.Keys and use container.GetCookies() for all keys. But I've had problems with that, because GetCookies expects Uri and not all my keys matched Uri pattern.

提交回复
热议问题