首页  ·  知识 ·  云计算
解决cookie中文乱码问题
网友  CIOZJ  综合  编辑:dezai   图片来源:网络
有时读取出来的cookie值中的中文部分可能是乱码,不管是有什么导致的,我们都可以通过编码进行解决 更改上面写入cookie的代码

下面是写入cookie的代码

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

 

下面是读取cookie的代码

[csharp]
if (Request.Cookies["username"]!=null)  
            {  
                string username = Request.Cookies["username"].Value;  
                Response.Write(username);  
            }  

 

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

更改上面写入cookie的代码

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

 

更改上面读取cookie的代码

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

本文作者:网友 来源:CIOZJ
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读