当前位置:编程学习 > C#/ASP.NET >>

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);
         }
     }

补充:asp.net教程,.Net开发
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,