首页 > 代码库 > Web如何使用cookie,MVC如何使用cookie
Web如何使用cookie,MVC如何使用cookie
1、创建Cookies有两种方法:
Response.Cookies["userName"].Value = http://www.mamicode.com/"patrick";Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");aCookie.Value =http://www.mamicode.com/ DateTime.Now.ToString();aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);
2、读取Cookie
if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);if(Request.Cookies["userName"] != null){ HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value);}
3、修改和删除Cookie
int counter;if (Request.Cookies["counter"] == null) counter = 0;else{ counter = int.Parse(Request.Cookies["counter"].Value);}counter++;Response.Cookies["counter"].Value =http://www.mamicode.com/ counter.ToString();Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);
一定要注意设置Cookies是用Response读取是用Request两者不一样!
删除Cookie
string subkeyName;subkeyName = "userName";HttpCookie aCookie = Request.Cookies["userInfo"];aCookie.Values.Remove(subkeyName);aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);
HttpCookie aCookie;string cookieName;int limit = Request.Cookies.Count;for (int i=0; i<limit; i++){ cookieName = Request.Cookies[i].Name; aCookie = new HttpCookie(cookieName); aCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(aCookie);}
Web如何使用cookie,MVC如何使用cookie
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。