关于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()))
http://support.microsoft.com/default.aspx?scid=kb;en-us;313282
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。