博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c# CookieContainer Cookie丢失bug、跨域问题等解决方案

Posted on 2012-12-21 15:42  快乐家++  阅读(2868)  评论(0编辑  收藏  举报

 

//修改域
public static CookieContainer InitCookie(CookieContainer cc)
{
CookieContainer coo = new CookieContainer();
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies)
{
c.Domain = ".qq.com";
coo.Add(c);

}
}
return coo;
}
 
//提取Cookie值
  public static string GetValueByCookieName(string key, CookieContainer cc)
        {
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies)
                    {
                        if (c.Name.ToLower() == key)
                        {
                            return c.Value;
                        }
                    }
            }
            return "";
        }