Asp.net教程

asp.net Cookie值中文乱码问题解决方法

本文主要是介绍asp.net Cookie值中文乱码问题解决方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
cookie里面不能写中文,是由于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
这篇关于asp.net Cookie值中文乱码问题解决方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
您可能喜欢