日期:2014-05-17  浏览次数:20576 次

cookies读写中文乱码
public static void WriteCookie(string strName, string strValue, bool cookieHttpOnly)
  {
  HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  if (cookie == null)
  {
  cookie = new HttpCookie(strName);
  }
  cookie.Value = strValue;
  cookie.HttpOnly = cookieHttpOnly;
  //System.Text.Encoding enc = System.Text.Encoding.GetEncoding("gb2312");
  HttpContext.Current.Response.AppendCookie(cookie);

  }

  public static string GetCookie(string strName)
  {
   
  if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  {
  return HttpContext.Current.Request.Cookies[strName].Value.ToString();
  }

  return "";
  }


WriteCookie("name", "中华人民共和国",30, false); 用getcookie读出就是乱码?如何解决

------解决方案--------------------
写入时候用HttpUtility.UrlEncode(); 编码

读取的时候用HttpUtility.UrlDecode(); 解码


------解决方案--------------------
JScript code
function getCookie(name)//取cookies函数        
{
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
   
     if(arr != null) return decodeURIComponent(arr[2]); return null;
    
}
alert(getCookie("A"));