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"]) + "
");
         Response.Write(Server.UrlDecode(Request.Cookies["GoodList"]["GoodsName"]) + "
");
}


中文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
阅读更多
换一批

没有更多推荐了,返回首页