天天看點

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