建站技术

当前位置:

ASP.NET中Cookies的用法

浏览量:

一, 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);

}


[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【27535611@qq.com】,我们在确认后,会立即删除,保证您的版权。