新版网站
C# .net中cookie值为中文时的乱码解决方法
发布时间:2013/10/15   已被3439人阅读    分享到:

一.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

本文分享地址:http://www.cn7080.com/news/82.html上海网站建设公司朗晟网络编辑,转发请注明来源及版权归属。
上一篇:没有了 【关闭】
下一篇:朗晟网络公司新版官方网站正式上线