-----------------------------------------------------操作-----------------------------------------------------------
1.添加cookies(用cookies方式去做sso,用户信息保存,修改都会依赖cookies)
HttpCookie cookies = new HttpCookie("Porschev");
cookies["name"] = "Zhong Wei";
cookies["sex"] = "1";
cookies.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(cookies);
}
#endregion
2.修改cookies( 在程序中难免会操作,对用户信息的修改,更新数据库后,也会修改cookies,为了修改后的显示)
方法一:
HttpCookie cookies = Request.Cookies["Porschev"];
cookies["name"] = "wilson Z";
}
#endregion
这是这次项目中遇到的“杯具”事件之一,当这样修改cookies时,在更新方法中再取这个名为Porschev的cookies,
name的值还为Zhong Wei而非wilson Z,页面显示也不对(己排除页面缓存原因,更新也确实没有成功)
修改方法一:
HttpCookie cookies = Request.Cookies["Porschev"];
cookies["name"] = "wilson Z";
//加上下面一句
Response.Cookies["Porschev"].Expires = DateTime.Now.AddMinutes(-1);
}
#endregion
自己理解:得让以前存入过期时间为20min的cookies失效
3.得到cookies (这个最简单,为求方法完整,还是写上吧)
HttpCookie cookies = Request.Cookies["Porschev"];
string name = cookies["name"]; //通过key取出对应value,多key同理取
}
#endregion
方法一:(最常用的一个删除cookies方法)
if (Request.Cookies["Porschev"] != null)
{
HttpCookie cookies = new HttpCookie("Porschev");
cookies.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookies);
}
}
#endregion
foreach (string cookiename in Request.Cookies.AllKeys)
{
HttpCookie cookies = Request.Cookies[cookiename];
if (cookies != null)
{
cookies.Expires = DateTime.Today.AddDays(-1);
Response.Cookies.Add(cookies);
Request.Cookies.Remove(cookiename);
}
}
}
#endregion
自己理解:方法一只能删除提当前Response中的cookies,不对完成删除掉客端的cookies,用遍历cookies的方式可以
方法一定对,己经过项目实际验证,观点不一定正确,如理解有误,请各位指正!!
新闻热点
疑难解答