解决cookie 不能存中文的方案

cookie 不支持中文 

解决方案非常容易    只需将其UrlEncode 一下即可,读取的时候要UrlDecode   方便起见,来个CookieHelper 类来操作

 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
 
namespace Sheb.Common
{
    public class CookieHelper 
    {
        /// <summary>
        /// 增加一个cookie 记录
        /// </summary>
        /// <param name="cookie"></param>
        public static void AddCookie(HttpCookie cookie)
        {
            DateTime dtNow = System.DateTime.Now;
            DateTime CookieExpries = cookie.Expires;
            TimeSpan span=  CookieExpries - dtNow;
 
            cookie.Value = HttpUtility.UrlEncode(cookie.Value);
 
            if (span.TotalDays < 0)
            {
                cookie.Expires = dtNow.AddDays(1);
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 判断是否有cookie 
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static bool HasCookie(string cookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie == null ||
                (cookie.Expires < System.DateTime.Now) && cookie.Expires != System.DateTime.MinValue)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 删除一个cookie 
        /// </summary>
        /// <param name="cookieName"></param>
        public static void DelCookie(string cookieName)
        {
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
                cookie.Expires = System.DateTime.Now.AddDays(1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
 
        /// <summary>
        /// 获得cookie 的值
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string GetCookieValue(string cookieName)
        {
            if (HasCookie(cookieName))
            {
                
                return HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[cookieName].Value);
            }
            else
            {
                return "";
            }
        }
    }
}

你可能感兴趣的:(cookie)