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