cookie中文乱码(转)

在Cookie的使用中,我们发现这样一个问题:如果写入Cookie的内容是中文(如用户称呼),用服务器端程序(如ASP或PHP)读出完全正确,但是用一般的javascript或VBScript的读Cookie函数取出的却是一堆乱码。这是一个棘手的问题,因为在有些情况下,Cookie的内容需要在客户机端用脚本语言读取。如果你写入了中文,得到了一堆乱码,是不是感觉很别扭呢?解决这个问题,还要从Cookie的存取方式说起。

下面是写入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读写操作中文时会出现乱码,有两个方法可以避免这种现象。 

1.    Server.UrlEncode, Server.UrlDecode

2.     HttpUtility.UrlEncode,HttpUtility.UrlDecode

 

对html进行编码的当然就要用到

 

1. Server.HtmlEncode ,Server.HtmlDecode

2. HttpUtility.HtmlEncode,HttpUtility.HtmlDecode

解决思路:

存cookie的时候要编码,那么取的时候再解码,编码和解码都要有,才不会出现乱码。 

 

转:http://www.cnblogs.com/sunrise/archive/2010/03/22/1691486.html

参考:http://blog.csdn.net/mynewdays/article/details/16119161

posted @ 2015-02-03 18:08  邹邹  Views(2177)  Comments(0)    收藏  举报