上方廣告

2008年10月28日 星期二

ASP.NET2.0 cookies中文寫入 在IE瀏覽器時會出現亂碼

運用UrlEncode編碼、UrlDecode解碼可解決此問題
//寫入cookies包含日期7天
HttpCookie cookie = new HttpCookie("Member");
cookie.Expires = DateTime.Now.AddDays(7);
cookie.Values["ID"] = HttpUtility.UrlEncode(txtUserName.Text.Trim());
Response.Cookies.Add(cookie);
//寫入cookies不包含日期
HttpCookie cookie = new HttpCookie("Member");
cookie.Values["ID"] = HttpUtility.UrlEncode(txtUserName.Text.Trim());
Response.Cookies.Add(cookie);
//讀取cookies
Label1.Text = HttpUtility.UrlDecode(Request.Cookies["Member"]["ID"]) ;

//刪除cookies
if (Request.Cookies["Member"] != null)
{
  HttpCookie cookie = new HttpCookie("Member");
  cookie.Expires = DateTime.Now.AddDays(-365);
  Response.Cookies.Add(cookie);
}