C# .net中cookie值为中文时的乱码解决方法

一.cookie的名称或子cookie的名称不能为中文,否则无法获得cookie

这个好办,名称不用中文即可

二.cookie的值为中文时候,取cookie的值会出现乱码

解决办法:存取cookie时候先解码和编码

存cookie,进行编码:

cookie.Value = HttpUtility.UrlEncode("上海");

取cookie时候,进行解码:
cookieValue = HttpUtility.UrlDecode(cookie.Value);

另外注意:

取子cookie时候,应该先解码,再根据%号分解,才能取到子cookie的值.

写Cookie里,一定要加上UrlEncode,用Request读Cookie时,一定要加上UrlDecode

示例如下:
protected void Page_Load(object sender, EventArgs e)
     {
         HttpCookie GoodList = null;

         //如果GoodList不为空,则GOODID+1,GoodsName加"乐无烟"
         if (Request.Cookies["GoodList"] != null)
         {
             GoodList = Request.Cookies["GoodList"];
             GoodList.Values["GoodsID"] = Server.UrlEncode(Server.UrlDecode(Request.Cookies["GoodList"]["GoodsID"]) + ",1");
             GoodList.Values["GoodsName"] = Server.UrlEncode(Server.UrlDecode(Request.Cookies["GoodList"]["GoodsName"]) + ",乐无烟");
             GoodList.Expires = DateTime.Now.AddDays(1);
             Response.Cookies.Add(GoodList);
         }
         else
         {
             //初次写入Cookie
             GoodList = new HttpCookie("GoodList");
             GoodList.Values["GoodsID"] = Server.UrlEncode("2");
             GoodList.Values["GoodsName"] = Server.UrlEncode("无烟锅");
             GoodList.Expires = DateTime.Now.AddDays(1);
             Response.Cookies.Add(GoodList);
         }

         Response.Write(Server.UrlDecode(Request.Cookies["GoodList"]["GoodsID"]) + "<br/>");
         Response.Write(Server.UrlDecode(Request.Cookies["GoodList"]["GoodsName"]) + "<hr/>");
}

中文cookie的问题,
在Windows 2000正常,
在Windows 2003 sp1下会偶尔出现乱码(遇到双字节特殊字符时候,例子:「`蹆绌 ),
在windows 2003 SP2下基本乱码

解决办法:
采用
Server.UrlEncode();
Server.UrlDecode();
Cookie["MyCookie"] = Server.UrlEncode("中文")
Response.Write(Server.UrlDecode(Request.Cookies("MyCookie").Value()))
编码和解码。


另外编码和解码要一致
System.Web.HttpUtility.UrlDecode 和 System.Web.HttpUtility.UrlEncode
System.Web.HttpContext.Current.Server.UrlDecode 和 System.Web.HttpContext.Current.Server.UrlEncode

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhdd1234/archive/2009/05/03/4145147.aspx

C# .net中cookie值为中文时的乱码解决方法,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。