码迷,mamicode.com
首页 > 其他好文 > 详细

解决cookie中文乱码问题

时间:2015-12-29 14:36:59      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

下面是写入cookie的代码

[csharp] view plaincopy
 
  1. HttpCookie cookie = new HttpCookie("username");  
  2.             cookie.Value = "张三,14,images/1.jpg";  
  3.             cookie.Expires = DateTime.Now.AddDays(1);  
  4.             Response.Cookies.Add(cookie);  


 

下面是读取cookie的代码

[csharp] view plaincopy
 
  1. if (Request.Cookies["username"]!=null)  
  2.             {  
  3.                 string username = Request.Cookies["username"].Value;  
  4.                 Response.Write(username);  
  5.             }  


 

有时读取出来的cookie值中的中文部分可能是乱码,不管是有什么导致的,我们都可以通过编码进行解决

更改上面写入cookie的代码

[csharp] view plaincopy
 
  1. HttpCookie cookie = new HttpCookie("username");  
  2.             cookie.Value = HttpUtility.UrlEncode("张三,14,images/1.jpg",Encoding.GetEncoding("UTF=8"));  
  3.             cookie.Expires = DateTime.Now.AddDays(1);  
  4.             Response.Cookies.Add(cookie);  


 

更改上面读取cookie的代码

[csharp] view plaincopy
 
    1. if (Request.Cookies["username"]!=null)  
    2.            {  
    3.                string username =HttpUtility.UrlDecode(Request.Cookies["username"].Value,Encoding.GetEncoding("UTF-8"));  
    4.                Response.Write(username);  
    5.            }  

解决cookie中文乱码问题

标签:

原文地址:http://www.cnblogs.com/hawk2014/p/5085545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!