天天看点

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