加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在CookieContainer中获取Cookie信息? (所有他们,不是

发布时间:2020-12-15 03:52:15 所属栏目:百科 来源:网络整理
导读:请看下面的代码: CookieContainer cookieJar = new CookieContainer();HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");request.CookieContainer = cookieJar;HttpWebResponse response = (HttpWebResponse)requ
请看下面的代码:
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;

如何在CookieJar中获取Cookie信息? (所有这些,不只是一个特定的领域.)
如何添加或删除一个cookie?

解决方法

可以使用反射来获取保存CookieContainer对象中所有域密钥的私有字段,

问:我如何获得该私人领域的名称?

答.使用反射器

它被宣布为:

private Hashtable m_domainTable;

一旦我们获得了私人领域,我们将获得域密钥,然后获取Cookie是一个简单的迭代.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Net;
using System.Collections;

namespace ConsoleApplication4
{


    static class Program
    {

        private static void Main()
        {

            CookieContainer cookies = new CookieContainer();
            cookies.Add(new Cookie("name1","value1","/","domain1.com"));
            cookies.Add(new Cookie("name2","value2","domain2.com"));

            Hashtable table = (Hashtable) cookies.GetType().InvokeMember("m_domainTable",BindingFlags.NonPublic |
                                                                         BindingFlags.GetField |
                                                                         BindingFlags.Instance,null,cookies,new object[] { });



            foreach (var key in table.Keys)
            {
                foreach (Cookie cookie in cookies.GetCookies(new Uri(string.Format("http://{0}/",key))))
                {
                    Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",cookie.Name,cookie.Value,cookie.Domain);
                }
            }


            Console.Read();
        }

    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读