C#操作cookie

创建Cookie

                   HttpCookie cookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
                    DateTime dt = DateTime.Now;
                    TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);//过期时间为1天
                    cookie.Expires = dt.Add(ts);//设置过期时间
                    cookie.Values.Add("uid", uid);  //添加cookie
                    Response.AppendCookie(cookie);

读取Cookie

         if (Request.Cookies["MyCook"] != null)
            {
                ViewData["Uid"] = Request.Cookies["MyCook"]["uid"]; //输出cookie
            }

修改Cookie

 //获取客户端的Cookie对象
    HttpCookie cookie= Request.Cookies["MyCook"];
        
    if (cookie!= null)
    {
      //修改Cookie的两种方法
      cookie.Values["uid"] = "134626655";
      cookie.Values.Set("userid", "134626655");

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

删除Cookie

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

设置Cookie过期的时间的TimeSpan

[Serializable]
public TimeSpan(
   int days,
   int hours,
   int minutes,
   int seconds
);

 

C#操作cookie

上一篇:关于mvc、webapi中get、post、put、delete的参数


下一篇:Windows环境的apache下Virtual Host 设置