首页  >  文章  >  后端开发  >  asp.net Cookie值中文乱码问题

asp.net Cookie值中文乱码问题

伊谢尔伦
伊谢尔伦原创
2016-11-25 09:14:551697浏览

ookie里面不能写中文,是由于cookie先天的编码方式造成的。所以需要有一种中间编码来过渡。 URLEncode是最好的选择。

我们以asp.net为例,代码如下:

设置Cookie时:

HttpCookie cookie = new HttpCookie("name", System.Web.HttpContext.Current.Server.UrlEncode("雨林星空"));
Response.Cookies.Add(cookie);

读取Cookie时:

if (Request.Cookies["name"] != null)
{
    Response.Write(System.Web.HttpContext.Current.Server.UrlDecode(Request.Cookies["name"].Value));
}

注意:编码和解码要一致

System.Web.HttpContext.Current.Server.UrlDecode 和 System.Web.HttpContext.Current.Server.UrlEncode

System.Web.HttpUtility.UrlDecode 和 System.Web.HttpUtility.UrlEncode


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn