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

  • 相关阅读:
    html5 鼠标跟随运动
    2018新年计划
    background-attachment:fixed不兼容性
    Javascript中常用方法简介
    FQ教程真实好用
    解决IE6 IE7绝对定位弹层被后面的元素遮住
    页面出现滚动条时,body里面的内容不能自动居中?
    怎么查看手机源码
    ES6入门教程---数值扩展和数组扩展
    ES6入门教程---解构赋值和字符串扩展
  • 原文地址:https://www.cnblogs.com/clc2008/p/2323423.html
Copyright © 2011-2022 走看看