C# 如何寫入cookie

  


//写入   protected void Button1_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 Button2_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);     }   }
 
模拟登录就用httpwebrequest HttpCookie UserCookie = new HttpCookie("") UserCookie.Value = ""; UserCookie.Expires = DataTime.Now.AddMonth(1); HttpContext.Response.Cookies.Add (UserCookie);

 

转载于:https://www.cnblogs.com/lh123/p/4059032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值