Server.UrlDecode不能解码Server.UrlEncode()?

今天被告知有个页面乱码。于是乎打开瞅瞅,那几个汉字是通过url参数传入的,传入之前已经用Server.UrlEncode()编码,貌似没什么问题。

有点怪。下了个断点,在监视中我写了这样的语句测试:

Server.UrlDecode(Server.UrlEncode(""))

出来是乱码……

不会吧!有一瞬间我感觉失去了方向,但是很快我猜到了问题所在,这肯定是某种编码指令的影响,于是打开这个页面的前台,检查它的Page指令,果然,看到一个CodePage="936",删之,再试,好了。

对于这一现象,我猜它们默认都使用utf-8编码,但是如果在前台显式指定了其它编码方式 ,在Encode的时候,就会以人工指定的编码方式来编码字符,可是在Decode的时候,仍然使用了utf-8,所以导致乱码。

为了验证这一猜测,反编译了System.Web.dll,看了一下其实现,很不幸,我只猜对了一半,Encode的代码如下:

    Encoding e = (this._context != null? this._context.Response.ContentEncoding : Encoding.UTF8;
    
return HttpUtility.UrlEncode(s, e);

Decode的代码:

    Encoding e = (this._context != null? this._context.Request.ContentEncoding : Encoding.UTF8;
    
return HttpUtility.UrlDecode(s, e);

看来强制的utf-8只是一个备用,那么在监视里再查一下当CodePage=936时,Request和Response的ContentEncoding是什么:
+  Request.ContentEncoding {System.Text.UTF8Encoding}
+  Response.ContentEncoding {System.Text.DBCSCodePageEncoding} 
怪不得会出乱码,原来指定了CodePage后Request和Response的编码是不一样的……


 

原文地址:https://www.cnblogs.com/Moosdau/p/1428130.html