asp.net 关于cookie的操作

一、无子键或单级cookie 读写
(1)、写入:
第一种
HttpCookie cookie=new HttpCookie("User");
cookie.Value="admin";
cookie.Expires=DateTime.Now.AddMinutes(1000);
HttpContext.Current.Response.AppendCookie(cookie);
或者
HttpContext.Current.Response.Cookies.Add(cookie);

第二种:
HttpContext.Current.Response.Cookies['User'].Value="admin";
HtttpContext.Current.Response.Cookies["User"].Exipres=DateTime.Now.AddMinutes(100);

(2)、读取
if(HttpContext.Current.Request.Cookies[key]!=null)
{
  string value=HttpContext.Current.Request.Cookies[key];
}
else
{
  string value="不存在"+key;
}
(3)、修改
if(HttpContext.Current.Request.Cookies[key]!=null)
{
  HttpCookie cookie=HttpCookie.Current.Request.Cookies[key];
  cookie.Value=value;
  HttpContext.Current.Response.Cookies.Add(cookie);
}
(4)、删除
if(HttpContext.Current.Request.Cookies[key]!=null)
{
  HttpCookie cookie=HttpContext.Current.Request.Cookies[key];
  cookie.Expires=DateTime.Now.AddMiuntes(time);//负数
  HttpContext.Current.Response.Cookies.Add(cookie);
}

二、有子键或多级cookie 读写

(1)、创建
HttpCookie cookie=new HttpCookie("user","admin");
或者
HttpCookie cookie=new HttpCookie("user");
cookie.Value="admin";
-------------------------------
cookie.Expires=DateTime.Now.AddMinutes(2);
cookie.Values["Name"]="Li";

cookie.Values.Add("Phone","12300000");
---------------------------------
HttpContext.Current.Response.Cookies.Add(cookie);

(2)、读取
if(HttpContext.Current.Request.Cookies[key]!=null)
{
  string value=HttpContext.Current.Request.Cookies[key][subkey] ?? "不存在:"+key+"->"+subkey;
}
else
{
  string value="不存在"+key;
}

(3)、修改
if(HttpContext.Current.Request.Cookies[key]!=null)
{
  HttpCookie cookie=HttpCookie.Current.Request.Cookies[key];
  cookie[subkey].Value=value;
  HttpContext.Current.Response.Cookies.Add(cookie);
}

 

转载于:https://www.cnblogs.com/coderblog/p/9067577.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值