cookie保存中文登錄賬號獲取時亂碼問題


登錄成功后寫入cookie的代碼

Response.Cookies["account"].Value = account;//"管理員"
Response.Cookies["account"].Expires = DateTime.Now.AddDays(14);

 

登錄前讀取cookie的代碼

if (Request.Cookies["account"] != null)
        ViewData["account"] = Request.Cookies["account"].Value;

一般來說如果我們存儲的Cookie值是英文的話這個寫法是沒問題的,但如果是中文,在讀取出來的時候則很可能會是亂碼。造成這個問題的原因一般都是編碼格式的問題(即保存時的編碼格式與讀取時的編碼格式不一致),所以只要我們統一保存與讀取的編碼格式就不會有這個問題了。

一般的解決辦法是統一用UTF-8的編碼格式:

登錄成功后寫入cookie的代碼

Response.Cookies["account"].Value = HttpUtility.UrlEncode(account, Encoding.GetEncoding("UTF-8"));//"管理員"
Response.Cookies["account"].Expires = DateTime.Now.AddDays(14);


登錄前讀取cookie的代碼

if (Request.Cookies["account"]!=null)
         ViewData["account"] =HttpUtility.UrlDecode(Request.Cookies["account"].Value, Encoding.GetEncoding("UTF-8"));
 
另外編碼和解碼要一致
System.Web.HttpUtility.UrlDecode 和 System.Web.HttpUtility.UrlEncode
System.Web.HttpContext.Current.Server.UrlDecode 和 System.Web.HttpContext.Current.Server.UrlEncode


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM