Cookie的创建、读取、删除

创建Cookie:

HttpCookie cookie =  new HttpCookie(COOKIE_NAME_FOR_USER);
cookie.Expires = DateTime.Now.AddYears(1);//设置日期
cookie[COOKIE_USER_NAME] = "用户名";
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

读取Cookie:

HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(COOKIE_NAME_FOR_USER);


删除Cookie:

System.Web.HttpContext.Current.Request.Cookies.Remove(COOKIE_NAME_FOR_USER)

另外,判断是否有cookie可以直接使用取的cookie和null进行比较,如果取出来非null就说明不为空

 

另外在一般处理程序中的使用方法:

  //写入cookie
  HttpCookie hc = new HttpCookie("time");
  hc.Value = DateTime.Now.ToString();
  hc.Expires = DateTime.Now.AddDays(7);
  context.Response.Cookies.Add(hc);

 

//读取Cookie
HttpCookie hc = context.Request.Cookies["time"]; if (hc != null) { context.Response.Write(hc.Value); } else { context.Response.Write("meiyou "); }


  //删除cookie 就是把cookie设置过期输出
  int count = context.Request.Cookies.Count;

  for (int i = 0; i < count; i++)
  {
     HttpCookie hc = context.Request.Cookies[i];     
     hc.Expires = DateTime.Now.AddDays(-1); //设置过期 
     context.Response.Cookies.Add(hc);
  }

 

转载于:https://www.cnblogs.com/xbblogs/p/4721476.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值