我是靠谱客的博主 聪明朋友,这篇文章主要介绍ASP.NET中cookie的几种创建和访问方法,现在分享给大家,希望可以做个参考。

来源:草根站长

Cookie (HttpCookie的实例)提供了一种在 Web 应用程序中存储用户特定信息的方法。例如,当用户访问您的站点时,您可以使用Cookie 存储用户首选项或其他信息。当该用户再次访问您的网站时,应用程序便可以检索以前存储的信息。

ASP.NET中的cookie:创建Cookie方法 (1)

Response.Cookies["userName"].Value = “admin";

Response.Cookies[“userName”].Expires = DateTime.Now.AddDays(1);

//如果不设置失效时间,Cookie信息不会写到用户硬盘,浏览器关闭将会丢弃。

ASP.NET中的cookie:创建Cookie方法 (2)

HttpCookie aCookie = new HttpCookie(“lastVisit”);

//上一次访问时间

aCookie.Value = DateTime.Now.ToString();

aCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(aCookie);

ASP.NET中的cookie:访问Cookie方法(1)

if(Request.Cookies["userName"] != null)

Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

访问Cookie方法(2)

if(Request.Cookies["userName"] != null) {

HttpCookie aCookie = Request.Cookies["userName"];

Label1.Text = Server.HtmlEncode(aCookie.Value);

}

ASP.NET中的cookie:创建多值Cookie方法 (1)

Response.Cookies["userInfo"]["userName"] = “admin";

Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();

Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

ASP.NET中的cookie:创建多值Cookie方法 (2)

HttpCookie aCookie = new HttpCookie("userInfo");

aCookie.Values["userName"] = “admin";

aCookie.Values["lastVisit"] = DateTime.Now.ToString();

aCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(aCookie);

ASP.NET中的cookie:读取多值Cookie

HttpCookie aCookie = Request.Cookies["userInfo"];

string userName=aCookie.Values[“userName”];

string lastVisit=aCookie.Values[“lastVisit”];

ASP.NET中的cookie:修改和删除Cookie

不能直接修改或删除Cookie,只能创建一个新的Cookie,发送到客户端以实现修改或删除Cookie。

ASP.NET中的cookie:修改

 HttpCookie aCookie = Request.Cookies["userInfo"];

aCookie.Values["userName"]="one_user";

或者aCookie.Values.Set("userName","one_user");

Response.AppendCookie(aCookie);

ASP.NET中的cookie:删除
 HttpCookie aCookie = Request.Cookies["userInfo"];

 aCookie.Values.Remove("userName");//移除键值为userName的值

TimeSpan ts = new TimeSpan(-1000);
 aCookie.Expires 
= DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在

 Response.AppendCookie(aCookie);

最后

以上就是聪明朋友最近收集整理的关于ASP.NET中cookie的几种创建和访问方法的全部内容,更多相关ASP.NET中cookie内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部