asp.net cookie操作类

作者:袖梨 2022-06-25
 代码如下 复制代码

public class BsCookie
   {
       //操作的cookie
       private HttpCookie _theCookie;
       //????ookie的名?
       private string _cookieName;
       private bool _httpOnly = true;
       ///


       /// 是否只允?在服?掌鞫嗽L??,默?只允?在服?斩嗽L??
       ///

       public bool HttpOnly
       {
           get { return _httpOnly; }
           set { _httpOnly = value; }
       }
       private double _expireMinutes;
       ///
       /// Cookies有效的存放?r?,以分?表示
       ///

       public double ExpireMinutes
       {
           get { return _expireMinutes; }
           set { _expireMinutes = value; }
       }
       public BsCookie(string name,double expireMinutes)
       {
           _cookieName = name;
           _expireMinutes = expireMinutes;
       }
       ///
       /// ?取????ookie
       ///

       ///
       ///
       private HttpCookie GetCookieReq()
       {
           HttpRequest request = HttpContext.Current.Request;
           if (request != null)
           {
               HttpCookie cookie = request.Cookies[_cookieName];
               if (cookie != null)
               {
                   return cookie;
               }
           }
           return null;
       }
       ///
       /// ?置????ookie
       ///

       ///
       ///
       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;
       }
       ///
       /// ?H?置主?的
       ///

       ///
       ///
       ///
       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);
           }          
       }
       ///
       /// ?置一?主?
       ///

       ///
       ///
       ///
       public void SetCookie(Hashtable keys)
       {
           _theCookie = GetCookieResponse();
           foreach (DictionaryEntry de in keys)
           {
               _theCookie.Values[de.Key.ToString()] = HttpUtility.HtmlEncode(AllCommon.Encrypt(de.Value.ToString()));
           }
       }
       ///
       /// ?取?我坏?ookie主?值
       ///

       ///
       /// 需要延?的cookie的默??r?
       ///
       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;
       }
       ///
       /// ?取一?????ookie值
       ///

       ///
       ///
       ///
       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;
       }
       ///
       /// 获取一组里面的单一个值
       ///

       ///
       ///
       ///
       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;
       }
       ///
       /// 清除????ookie
       ///

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

相关文章

精彩推荐