关于Asp.net应用中cookie的问题处理
1、在应用程序中有时会出现cookie混乱的问题,主要问题在RemoveCookie上,解决办法:
/// <summary>
/// 移除cookie,将Request和Response两个集合中的都清理
/// Code by KentLi
/// </summary>
/// <param name="cookieName">cookie名称</param>
public void RemoveCookie(string cookieName)
{
HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
if (Cookie != null)
{
Cookie.Expires= DateTime.Now;
HttpContext.Current.Request.Cookies.Remove(cookieName);
}
Cookie = HttpContext.Current.Response.Cookies[cookieName];
if (Cookie != null)
{
Cookie.Expires= DateTime.Now;
HttpContext.Current.Response.Cookies.Remove(cookieName);
}
}
public void appendcook(string cookies,string cookiesvalue,int days)
{
HttpCookie usercookie=new HttpCookie(cookies,cookiesvalue);
usercookie.Expires = DateTime.Now.AddDays(days);
HttpContext.Current.Response.Cookies.Add(usercookie);
}
2、中文cookie的问题,在Windows 2000正常,在Windows 2003有时会不正常(几率很小,但的确存在),采用:
Server.UrlEncode();
Server.UrlDecode();
编码和解码。
Cookie["MyCookie"] = Server.UrlEncode("中文")
Response.Write(Server.UrlDecode(Request.Cookies("MyCookie").Value()))
3.彻底删除cookie
protected void DeleteCookie(string cookieName)
{
if (Request.Cookies[cookieName] != null)
{
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Expires = DateTime.Now.AddDays(-1);
Response.AppendCookie(cookie);//这句很重要
}
}
http://support.microsoft.com/default.aspx?scid=kb;en-us;313282
更多Cookie的相关知识
HttpContext.Current.Response.Cookies
HttpContext.Current.Request.Cookies
分别是需要写回用户客户端和从用户客户端读取的Cookie集合。
当修改Cookie的时候,为了保证同一个Asp.net 页面能访问修改后的Cookie,就必须同时修改这两个集合中的Cookie。
http://blog.joycode.com/ghj/archive/
http://west-wind.com/weblog/posts/1006.aspx
http://www.derkeiler.com/Newsgroups/microsoft.public.inetserver.iis.security/2004-03/0147.html