• 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()))

  • 相关阅读:
    lintcode 最长上升连续子序列 II(二维最长上升连续序列)
    lintcode 滑动窗口的最大值(双端队列)
    windows下实现Git在局域网使用
    eclipse导入web项目之后项目中出现小红叉解决办法
    HTTP协议基础
    c++面试常用知识(sizeof计算类的大小,虚拟继承,重载,隐藏,覆盖)
    Codeforces Round #327 (Div. 2) B. Rebranding C. Median Smoothing
    c语言表白程序代码
    矩阵的逆矩阵,伴随矩阵
    document.getElementById()与 $()区别
  • 原文地址:https://www.cnblogs.com/clc2008/p/2323423.html
Copyright © 2020-2023  润新知