asp.net

ASP.NET中Cookies的用法

2013-04-23

一, cookies 写入

方法1: 
Response.Cookies["username"].Value="gjy"; 
Response.Cookies["username"].Expires=DateTime.Now.AddDays(1); 

方法2: 
System.Web.HttpCookie newcookie=new HttpCookie("username"); 
newcookie.Value="gjy"; 
newcookie.Expires=DateTime.Now.AddDays(1); 
Response.AppendCookie(newcookie);

 

创建带有子键的cookies: 
System.Web.HttpCookie newcookie=new HttpCookie("user"); 
newcookie.Values["username"]="gjy"; 
newcookie.Values["password"]="111"; 
newcookie.Expires=DateTime.Now.AddDays(1); 
Response.AppendCookie(newcookie);

或者

HttpCookie UserCookie = new HttpCookie("KindCode");
UserCookie["bigKind"] = lstBigKindCode.SelectedValue.Trim();
UserCookie["smallKind"] = lstSmallKindCode.SelectedValue.Trim();
UserCookie["UserName"] = strUserName;
UserCookie["userKind"] = lsbUserSmallKindCode.SelectedValue;
UserCookie.Expires = DateTime.Now.AddDays(1);//这里设置要保存多长时间.
Response.Cookies.Add(UserCookie);

 

二,cookies的读取: 

无子键读取: 
if(Request.Cookies["username"]!=null) 

Response.Write(Server.HtmlEncode(Request.Cookies["username"].Value)); 


有子键读取: 
if(Request.Cookies["user"]!=null) 

Response.Write(Server.HtmlEncode(Request.Cookies["user"]["username"].Value));

}

或者

HttpCookie cookie = Request.Cookies["KindCode"];
if (cookie != null)
{
string bigKind = cookie.Values["bigKind"];
string userName = cookie.Values["UserName"];

}

三,cookies的清除

HttpCookie cookie = Request.Cookies["KindCode"];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-2);
Response.Cookies.Set(cookie);

}