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

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

  • 相关阅读:
    EF6的多线程与分库架构设计实现
    Windows环境下安装Ionic
    Win7 下安装RabbitMQ
    在VS Nuget命令行下进行EF数据库迁移
    WebSocket与Tcp连接
    常用浏览器内核
    异步代码
    TCP与UDP的区别
    二分查找(折半查找)
    顺序查找
  • 原文地址:https://www.cnblogs.com/LiaoHao/p/3140108.html
Copyright © 2011-2022 走看看