[普通]cookie保存中文登录账号获取时乱码问题

作者(passion) 阅读(1170次) 评论(0) 分类( ASP.NET)

登录成功后写入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
« 上一篇:wifi共享上网(至尊版wifi)
« 下一篇:ASP.NET附加数据库文件的方式,如何发布到IIS7而不导致SQLServer出错
在这里写下您精彩的评论
  • 微信

  • QQ

  • 支付宝

返回首页
返回首页 img
返回顶部~
返回顶部 img