zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    android调用google地图
    AndroidManifest.xml中android:configChanges的简介
    android消息推送机制
    用j4lChartAndroid实现3D图饼
    读《重构改善既有代码的设计》笔记一
    怎样删除data下的多余文件
    Mac OSX 10.8 下 配置 mysql+python+thrift开发环境
    新的征程
    练习1 四则运算的程序
    作业二四则运算
  • 原文地址:https://www.cnblogs.com/xlhblogs/p/2862421.html
Copyright © 2011-2022 走看看