zoukankan      html  css  js  c++  java
  • net2.0中使用Cookie保存中文出现乱码的解决方法

    今天朋友注册会员账号使用了中文,登陆后发现用户名变成了乱码,后来发现是因为账号直接用cookie保存的,而cookie对中文不支持才导致乱码的情况。下面的代码是在网上找的
    设置cookie时:

    HttpCookie cookie = Request.Cookies["UserName"];
                    if (Session["UserName"] != null)
                    {
                        string userName = Server.UrlEncode(Session["UserName"].ToString());
                        if (cookie != null)
                        {
                            cookie.Value = userName;
                            //cookie.Expires = DateTime.Now.AddDays(1);
                            cookie.Domain = BasePage.DomainName;
                            Response.Cookies.Set(cookie);
                        }
                        else
                        {
                            cookie = new HttpCookie("UserName");
                            cookie.Value = userName;
                            //cookie.Expires = DateTime.Now.AddDays(1);
                            cookie.Domain = BasePage.DomainName;
                            Response.Cookies.Add(cookie);
                        }
                    }


    获取cookie时:

    private string _loginUserName;
            public string LoginUserName
            {
                get
                {
                    if (Session["UserName"] != null && Session["UserName"].ToString() != "")
                    {
                        _loginUserName = Session["UserName"].ToString();
                    }
                    else if (Request.Cookies["UserName"] != null && Request.Cookies["UserName"].Value != "")
                    {
                        _loginUserName = Server.UrlDecode(Request.Cookies["UserName"].Value);
                    }
                    else
                    {
                        _loginUserName = null;
                    }
                    return _loginUserName;
                }
            }

    还有一个条件,即配置文件中需要设置中文格式,如:

    <!-- 全球化          此节设置应用程序的全球化设置。    -->
    <globalization requestEncoding="GB2312" responseEncoding="GB2312"/>

    ---------------------------------------------------------------------------------------------------------------------------

    中文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()))

  • 相关阅读:
    架构设计
    Asp.net MVC突然变慢,缓存消失的一种原因
    B2C电子商务系统研发——商品SKU分析和设计(二)
    ASP.NET MVC下基于异常处理的完整解决方案
    【C#.NET】利用FastDFS打造分布式文件系统
    C#
    50个必备的实用jQuery代码段
    可视化组件库(The Visual Component Library)
    TortoiseHg 2.2.2
    企业信息开发平台
  • 原文地址:https://www.cnblogs.com/clc2008/p/2323423.html
Copyright © 2011-2022 走看看