Cookie存中文乱码的问题

有个奇怪的问题:登录页面中使用Cookie存值,Cookie中要存中文汉字。代码在本地调试,一切OK,汉字也能顺利存到Cookie和从Cookie中读出,但是放到服务器上不管用了,好好的汉字成了乱码,原本以为是服务器环境和本地的不一样,后来一想应该不对,因为代码放服务器上之后再访问登录页面会和服务器交互,交互必然要有网络传输,而Cookie是存在本地的,就是在服务器向本地写Cookie的时候,网络的编码格式影响了汉字的正常存储导致汉字乱码。顺着这个思路改代码,然后测试,通过!

但是新问题来了,在给汉字编码的时候,常用的有这两种:HttpUtility.UrlEncode 和 Server.UrlEncode,虽然编码/解码成对使用没问题,但是毕竟是两种方法,总该是有区别的,网上查了一下,区别如下:

第一:引用:

1、HttpUtility.UrlEncode,HttpUtility.UrlDecode是静态方法,而Server.UrlEncode,Server.UrlDecode是实例方法。
2、Server是HttpServerUtility类的实例,是System.Web.UI.Page的属性。
3、用HttpUtility.UrlEncode编码后的字符串和用Server.UrlEncode进行编码后的字符串对象不一样

Server.UrlEncode 可以根据你页面定义好的编码方式进行编码。

而 HttpUtility.UrlDecode则默认以utf8来编码。 不然你需要自己指定编码方式:

Encoding gb2312= Encoding.GetEncoding("gb2312");

string v5= HttpUtility.UrlEncode("中文汉字", gb2312);

而 Server.UrlDecode则默认调用web.config中<globalization />节点中指定来编码

<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" />

string v3= Server.UrlEncode("中文汉字");

这两种方式,在不使用web.config默认的编码方式时,HttpUtility.UrlEncode比较好用,但是不方便;如果是使用web.config统一编码,则Server.UrlDecode比较好。另外就是,如果是下载文件而定义编码方式,最好使用HttpUtility.UrlEncode

原文地址:https://www.cnblogs.com/sunny-539/p/6387301.html