ASP.NET 操作 cookie 防止中文乱码, 解决中文乱码问题

设置 cookie
        protected void Button1_Click(object sender, EventArgs e)
        {
            // 设置 cookie, 将内容进行编码存储
            HttpCookie cookie = new HttpCookie("cookie", HttpUtility.UrlEncode("中文/abc"));
            // 过期时间
            cookie.Expires = DateTime.Now.AddDays(+1);
            Response.Cookies.Add(cookie);

            Response.Redirect("Default.aspx");
        }


获取 cookie

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = default(HttpCookie);
            cookie = Request.Cookies.Get("cookie");

            // 判断是否为空
            if (cookie != null)
            {
                // 进行解码
                string str = HttpUtility.UrlDecode(cookie.Value);
                Response.Write(str);
            }
            else
            {
                // cookie 对象为空
            }
        }


热门推荐