asp.net cookie操作类

 代码如下 复制代码

public class BsCookie
   {
       //操作的cookie
       private HttpCookie _theCookie;
       //????ookie的名?
       private string _cookieName;
       private bool _httpOnly = true;
       /// <summary>
       /// 是否只允?在服?掌鞫嗽L??,默?只允?在服?斩嗽L??
       /// </summary>
       public bool HttpOnly
       {
           get { return _httpOnly; }
           set { _httpOnly = value; }
       }
       private double _expireMinutes;
       /// <summary>
       /// Cookies有效的存放?r?,以分?表示
       /// </summary>
       public double ExpireMinutes
       {
           get { return _expireMinutes; }
           set { _expireMinutes = value; }
       }
       public BsCookie(string name,double expireMinutes)
       {
           _cookieName = name;
           _expireMinutes = expireMinutes;
       }
       /// <summary>
       /// ?取????ookie
       /// </summary>
       /// <param name="name"></param>
       /// <returns></returns>
       private HttpCookie GetCookieReq()
       {
           HttpRequest request = HttpContext.Current.Request;
           if (request != null)
           {
               HttpCookie cookie = request.Cookies[_cookieName];
               if (cookie != null)
               {
                   return cookie;
               }
           }
           return null;
       }
       /// <summary>
       /// ?置????ookie
       /// </summary>
       /// <param name="name"></param>
       /// <returns></returns>
       private HttpCookie GetCookieResponse()
       {
           HttpResponse response = HttpContext.Current.Response;
           HttpCookie cookie = GetCookieReq();
           if (cookie != null)
           {
               string value = cookie.Value;
               cookie = response.Cookies[_cookieName];
               cookie.Value = value;
           }
           else
           {
               cookie = new HttpCookie(_cookieName);
               cookie.HttpOnly = _httpOnly;
               response.Cookies.Add(cookie);
           }
           if (Math.Abs(_expireMinutes) > 1 && cookie != null)//在存在的情?r的下,延??期日期
           {
               cookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
           }
           return cookie;
       }
       /// <summary>
       /// ?H?置主?的
       /// </summary>
       /// <param name="name"></param>
       /// <param name="value"></param>
       /// <param name="exMinutes"></param>
       public void SetCookie(string value)
       {
           _theCookie = GetCookieResponse();
           _theCookie.Value = HttpUtility.HtmlEncode(AllCommon.Encrypt(value));
           if (Math.Abs(_expireMinutes) > 1)
           {
               _theCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
           }          
       }
       /// <summary>
       /// ?置一?主?
       /// </summary>
       /// <param name="name"></param>
       /// <param name="keys"></param>
       /// <param name="exMinutes"></param>
       public void SetCookie(Hashtable keys)
       {
           _theCookie = GetCookieResponse();
           foreach (DictionaryEntry de in keys)
           {
               _theCookie.Values[de.Key.ToString()] = HttpUtility.HtmlEncode(AllCommon.Encrypt(de.Value.ToString()));
           }
       }
       /// <summary>
       /// ?取?我坏?ookie主?值
       /// </summary>
       /// <param name="name"></param>
       /// <param name="exMinutes">需要延?的cookie的默??r?</param>
       /// <returns></returns>
       public string GetCookie()
       {
           _theCookie = GetCookieReq();
           if (_theCookie == null)
           {
               return string.Empty;
           }
           string thevalue = AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Value));
           if (thevalue.Length > 0)
           {
               HttpCookie serverCookie = GetCookieResponse();
           }
           return thevalue;
       }
       /// <summary>
       /// ?取一?????ookie值
       /// </summary>
       /// <param name="name"></param>
       /// <param name="exMinutes"></param>
       /// <returns></returns>
       public Hashtable GetCookiesKeys()
       {
           _theCookie = GetCookieReq();
           if (_theCookie == null)
           {
               return null;
           }           
           string[] keys = _theCookie.Values.AllKeys;
           if (keys.Length > 0)
           {
               Hashtable keyHash = new Hashtable();
               foreach (string key in keys)
               {
                   keyHash.Add(key, AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Values[key])));
               }
               HttpCookie serverCookie = GetCookieResponse();
               return keyHash;
           }
           return null;
       }
       /// <summary>
       /// 获取一组里面的单一个值
       /// </summary>
       /// <param name="keyname"></param>
       /// <param name="exMinutes"></param>
       /// <returns></returns>
       public string GetCookieKV(string keyname)
       {
           _theCookie = GetCookieReq();
           if (_theCookie == null)
           {
               return string.Empty;
           }
           string result=AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Values[keyname]));
           if (result.Length > 0)
           {
               HttpCookie serverCookie = GetCookieResponse();
              
           }
           return result;
       }
       /// <summary>
       /// 清除????ookie
       /// </summary>
       public void clearCookie()
       {
           HttpCookie serverCookie = GetCookieResponse();
           if (serverCookie != null)
           {
               serverCookie.Expires = DateTime.Now.AddDays(-1.0d);
           }
       }
   }

 操作详解cookie 写入、读取、修改、删除

 

 代码如下 复制代码

//写入
    protected void Button2_Click(object sender, EventArgs e)
     {
         HttpCookie cookie=new HttpCookie("MyCook");//初使化并设置Cookie的名称
         DateTime dt=DateTime.Now;
         TimeSpan ts = new TimeSpan(0, 0, 1,0,0);//过期时间为1分钟
         cookie.Expires = dt.Add(ts);//设置过期时间
         cookie.Values.Add("userid", "userid_value");
         cookie.Values.Add("userid2","userid2_value2");
         Response.AppendCookie(cookie);
        //输出该Cookie的所有内容
        //Response.Write(cookie.Value); //输出为:userid=userid_value&userid2=userid2_value2
     }

    //读取
    protected void Button1_Click(object sender, EventArgs e)
     {

       // HttpCookie cokie = new HttpCookie("MyCook");//初使化
        if (Request.Cookies["MyCook"]!=null)
         {
            //Response.Write("Cookie中键值为userid的值:" + Request.Cookies["MyCook"]["userid"]);//整行
            //Response.Write("Cookie中键值为userid2的值" + Request.Cookies["MyCook"]["userid2"]);
             Response.Write(Request.Cookies["MyCook"].Value);//输出全部的值
         }
     }

    //修改Cookie
    protected void Button3_Click(object sender, EventArgs e)
     {
        //获取客户端的Cookie对象
         HttpCookie cok = Request.Cookies["MyCook"];
       
        if (cok != null)
         {
         //修改Cookie的两种方法
             cok.Values["userid"] = "alter-value";
             cok.Values.Set("userid", "alter-value");

          //往Cookie里加入新的内容
              cok.Values.Set("newid", "newValue");
              Response.AppendCookie(cok);
         }

     
     }
    //删除Cookie
    protected void Button4_Click(object sender, EventArgs e)
     {

         HttpCookie cok = Request.Cookies["MyCook"];
        if (cok != null)
         {
            if (!CheckBox1.Checked)
             {
                 cok.Values.Remove("userid");//移除键值为userid的值
             }
            else
             {
                 TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
                 cok.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在
             }
             Response.AppendCookie(cok);
         }
     }

时间: 2024-10-24 16:46:20

asp.net cookie操作类的相关文章

asp.net Cookie操作类_实用技巧

复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Data; using System.Configu

一个.net下通用的Cookie操作类

笔者曾经参与一个大型多用户商城的开发,系统用户角色很多,有买家,卖家,代理商,系统管理员 ,普通管理员,超级管理员等,这些用户都涉及到登陆系统,然后建立cookies的问题,由于角色的不同 ,这些用户登陆系统后,所建的cookies都相对独立,而且对一个多用户商城来说,cookies区分域很重要 ,不同的域名要建不同的域.因此笔者在开发的过程中,写了很多次的建cookies,取cookies的代码,不 胜其烦! 既然都是建cookies,那么肯定有共同点,我们何不抽象出来,写一个通用的Cooki

javascript cookie操作类的实现代码小结附使用方法_javascript技巧

第一种方法:cookie操作类,代码封装了,下面也有使用方法,大家可以参考下. 复制代码 代码如下: String.prototype.Trim = function() { return this.replace(/^\s+/g,"").replace(/\s+$/g,""); } function JSCookie() { this.GetCookie = function(key) { var cookie = document.cookie; var coo

ASP.NET Cookie 操作实现_实用技巧

ASP.NET Cookie 概述 Cookie 提供了一种在 Web 应用程序中存储用户特定信息的方法.例如,当用户访问您的站点时,您可以使用 Cookie 存储用户首选项或其他信息.当该用户再次访问您的网站时,应用程序便可以检索以前存储的信息. 什么是 Cookie? Cookie 是一小段文本信息,伴随着用户请求和页面在 Web 服务器和浏览器之间传递.Cookie 包含每次用户访问站点时 Web 应用程序都可以读取的信息. 例如,如果在用户请求站点中的页面时应用程序发送给该用户的不仅仅是

ASP通用数据库操作类源代码

<%'=========================================================================='文件名称:clsDbCtrl.asp'功 能:数据库操作类'作 者:coldstone (coldstone[在]qq.com)'程序版本:v1.0.5'完成时间:2005.09.23'修改时间:2007.10.30'版权声明:可以在任意作品中使用本程序代码,但请保留此版权信息.'          如果你修改了程序中的代码并得到更好的应用,

ASP Crazy 模版操作类(最简单的模板类、仅提供交流)_应用技巧

文件名:Awa_temp.Class.asp 复制代码 代码如下: <% 'Crazy蛙!模板操作类 '作者Crazy~蛙! QQ:379969387 欢迎交流 '版本V1.0; Class AwaTemp Public aa Private FSO,StrTemp,FileData,GetDatas,StrHtmlName,htmlwrite,StrLabel,StrLValues '=========================================== '构造函数_初始化FS

ASP Crazy 模版操作类(最简单的模板类、仅提供交流)

文件名:Awa_temp.Class.asp 复制代码 代码如下: <% 'Crazy蛙!模板操作类 '作者Crazy~蛙! QQ:379969387 欢迎交流 '版本V1.0; Class AwaTemp Public aa Private FSO,StrTemp,FileData,GetDatas,StrHtmlName,htmlwrite,StrLabel,StrLValues '=========================================== '构造函数_初始化FS

mysql仿asp的数据库操作类_Mysql

<?php  class MySQLDB    {      //MYSQL数据库操作类      //作者:熊毅      //版本:2.0(发行版)        查询数据时Query后可以用GetValue得到相应的值,既可以是字段名也可以是已0开始的序号  插入新值,先用AddNew后使用SetValue相应的字段名或序号和字段值,在用Update添加  编辑时用Edit指定编辑记录的条件在使用SetValue,最后用Update添加  在类使用过程中,sTName记录上次使用的数据库表

ASP对Cookie操作的详细讲解

cookie Cookie是一种发送到客户浏览器的文本串句柄,并保存在客户机硬盘上,可以用来在某个Web站点会话之间持久地保持数据.Request和Response对象都有一组Cookie.Request.cookie集合是一系列Cookie,从客户端与HTTP Request一起发送到Web服务器.反过来,如果你希望把Cookie发送到客户机,就可以使用Response.cookie1.ExpiresAbsolute属性 该属性可以赋一个日期,过了这个日期Cookie就不能再被使用了.通过给E