Request 接收参数乱码原理解析

摘要:
无论您如何使用System.Web.HttpUtility.UrlDecode对其进行解码,它都是无效的。原理描述:1:首先,Ext.js会在提交时对客户端的url参数进行编码并重新提交,客户端的编码默认为utf-8。默认情况下,客户端有三个编码函数:escape()encodeURI()encodiURIComponent()2:为什么在使用Request时会收到乱码。QueryString[“xxx”]是否接收参数?为此,我们必须对请求的原始处理逻辑过程进行反编译。QueryString一步一步。2.1:查看QueryString属性的代码:publicNameValueCollectionQueryString{get{if{this._QueryString=newHttpValueCollection();if(this._wr!=0){this._QueryString.FillFromEncodedBytes;}}//以上是流式字节的处理,即文件上载等。

起因:

今天早上被同事问了一个问题:说接收到的参数是乱码,让我帮着解决一下。

实际情景:

Request 接收参数乱码原理解析第1张Request 接收参数乱码原理解析第2张
同事负责的平台是Ext.js框架搭建的,web.config配置文件里配置了全局为“GB2312”编码:

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

当前台提交“中文文字”时,后台用Request.QueryString[
"xxx"]接收到的是乱码。

无论用System.Web.HttpUtility.UrlDecode(
"xxx","编码类型")怎么解码都无效。

原理说明:

1:首先确定的是:客户端的url参数在提交时,Ext.js会对其编码再提交,而客户端的编码默认是utf-8编码

客户端默认有三种编码函数:escape() encodeURI() encodeURIComponent()

2:那为什么用Request.QueryString["xxx"]接收参数时,收到的会是乱码?

为此,我们必须解开Request.QueryString的原始处理逻辑过程

我们步步反编绎,

2.1:看QueryString属性的代码:

Request 接收参数乱码原理解析第3张Request 接收参数乱码原理解析第4张
public NameValueCollection QueryString
{
    
get
    {
        
if (this._queryString == null)
        {
            
this._queryString = new HttpValueCollection();
            
if (this._wr != null)
            {
                
this.FillInQueryStringCollection();//重点代码切入点
            }
            
this._queryString.MakeReadOnly();
        }
        
if (this._flags[1])
        {
            
this._flags.Clear(1);
            ValidateNameValueCollection(
this._queryString, "Request.QueryString");
        }
        
return this._queryString;
    }
}

2.2:切入 FillInQueryStringCollection()方法

Request 接收参数乱码原理解析第5张Request 接收参数乱码原理解析第6张
private void FillInQueryStringCollection()
{
    
byte[] queryStringBytes = this.QueryStringBytes;
    
if (queryStringBytes != null)
    {
        
if (queryStringBytes.Length != 0)
        {
            
this._queryString.FillFromEncodedBytes(queryStringBytes, this.QueryStringEncoding);
        }
    }
//上面是对流字节的处理,即文件上传之类的。
    else if (!string.IsNullOrEmpty(this.QueryStringText))
    {
        
//下面这句是对普通文件提交的处理:FillFromString是个切入点,编码切入点是:this.QueryStringEncoding
        this._queryString.FillFromString(this.QueryStringText, truethis.QueryStringEncoding);
        
    }
}

2.3:切入:QueryStringEncoding

Request 接收参数乱码原理解析第7张Request 接收参数乱码原理解析第8张
internal Encoding QueryStringEncoding
{
    
get
    {
        Encoding contentEncoding 
= this.ContentEncoding;
        
if (!contentEncoding.Equals(Encoding.Unicode))
        {
            
return contentEncoding;
        }
        
return Encoding.UTF8;
    }
}
//点击进入this.ContentEncoding则为:
public Encoding ContentEncoding
{
    
get
    {
        
if (!this._flags[0x20|| (this._encoding == null))
        {
            
this._encoding = this.GetEncodingFromHeaders();
            
if (this._encoding == null)
            {
                GlobalizationSection globalization 
= RuntimeConfig.GetLKGConfig(this._context).Globalization;
                
this._encoding = globalization.RequestEncoding;
            }
            
this._flags.Set(0x20);
        }
        
return this._encoding;
    }
    
set
    {
        
this._encoding = value;
        
this._flags.Set(0x20);
    }
}

说明:

从QueryStringEncoding代码得出,系统默认会先取globalization配置节点的编码方式,如果取不到,则默认为UTF-8编码方式

2.4:切入  FillFromString(string s, bool urlencoded, Encoding encoding)

Request 接收参数乱码原理解析第9张Request 接收参数乱码原理解析第10张代码有点长,就折叠起来了
internal void FillFromString(string s, bool urlencoded, Encoding encoding)
{
    
int num = (s != null? s.Length : 0;
    
for (int i = 0; i < num; i++)
    {
        
int startIndex = i;
        
int num4 = -1;
        
while (i < num)
        {
            
char ch = s[i];
            
if (ch == '=')
            {
                
if (num4 < 0)
                {
                    num4 
= i;
                }
            }
            
else if (ch == '&')
            {
                
break;
            }
            i
++;
        }
        
string str = null;
        
string str2 = null;
        
if (num4 >= 0)
        {
            str 
= s.Substring(startIndex, num4 - startIndex);
            str2 
= s.Substring(num4 + 1, (i - num4) - 1);
        }
        
else
        {
            str2 
= s.Substring(startIndex, i - startIndex);
        }
        
if (urlencoded)//外面的传值默认是true,所以会执行以下语句
        {
            
base.Add(HttpUtility.UrlDecode(str, encoding), HttpUtility.UrlDecode(str2, encoding));
        }
        
else
        {
            
base.Add(str, str2);
        }
        
if ((i == (num - 1)) && (s[i] == '&'))
        {
            
base.Add(nullstring.Empty);
        }
    }
}

说明:

从这点我们发现:所有的参数输入,都调用了一次:HttpUtility.UrlDecode(str2, encoding);

3:结论出来了

当客户端js对中文以utf-8编码提交到服务端时,用Request.QueryString接收时,会先以globalization配置的gb2312去解码一次,于是,产生了乱码。

所有的起因为:

1:js编码方式为urt-8

2:服务端又配置了默认为gb2312

3:Request.QueryString默认又会调用HttpUtility.UrlDecode用系统配置编码去解码接收参数。

文章补充

Request 接收参数乱码原理解析第11张Request 接收参数乱码原理解析第12张
1:系统取默认编码的顺序为:http请求头->globalization配置节点-》默认UTF-8

2:在Url直接输入中文时,不同浏览器处理方式可能不同如:ie不进行编码直接提交,firefox对url进行gb2312编码后提交。

3:对于未编码“中文字符”,使用Request.QueryString时内部调用HttpUtility.UrlDecode后,由gb2312->utf-8时,

如果查不到该中文字符,默认转成
"%ufffd",因此出现不可逆乱码。

4:解决之路

知道了原理,解决的方式也有多种多样了:

1:全局统一为UTF-8编码,省事又省心。

 

2:全局指定了GB2312编码时,url带中文,js非编码不可,如ext.js框架。

这种方式你只能特殊处理,在服务端指定编码解码,
因为默认系统调用了一次HttpUtility.UrlDecode("xxx",系统配置的编码),
因此你再调用一次HttpUtility.UrlEncode("xxx",系统配置的编码),返回到原始urt
-8编码参数
再用HttpUtility.UrlDecode("xxx",utf-8),
解码即可。

5:其它说明:默认对进行一次解码的还包括URI属性,而Request.RawUrl则为原始参数

最后做一下链接:路过秋天版博客 V2.0 测试版发布 公测一周

免责声明:文章转载自《Request 接收参数乱码原理解析》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇树莓派搭建Nexus2私服Lambda 表达式下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

转:利用JavaScript实现图片标注——SearchMapIdentityTask

功能:功能实现了现在网络流行的定位后在地图上画一个图标,点击图标后弹出消息框。...

iOS学习——内存泄漏检查及原因分析

由于我刚刚加入项目团队,我不熟悉所讨论的模块的代码,所以当我遇到问题时,我感到非常困难。此外,作为一名iOS新手,我真的不知道如何排除内存泄漏以及原因。因此,我也借此机会研究了iOS开发中内存泄漏的故障排除方法和原因分析。尽管当前的iOS开发基本上采用ARC模式进行内存管理,但如果不小心,就会发生内存泄漏。...

zookeeper 日志输出到指定文件夹

最近,我在学习ZookeperStormKafka。顺便说一下,我在本地建立了一个集群。我遇到了Zookeeper日志输出路径的问题。我发现设置log4j。Zookeeper中的属性无法解决日志路径问题。我发现解决方案如下:1.修改log4j属性,您应该能够更改它。我更改了红色粗体,但仍然没有生效。#定义要移动的默认值...

用python调用caffe时出错:AttributeError: 'module' object has no attribute 'bool_'

下面给出了一个解决方案,即重命名冲突的io文件:numpyと PyCaffe公司が io。年が 竞争す る よ で す$ pythonclassify。py--raw_scale255~/caffe/101_ObjectCategories/airaires/image_0001.jpg../result.npyTraceback:文件“classif.py...

Android:在任务列表隐藏最近打开的app

//schemas.android.com/apk/res/android“package=”com.li.test“android:versionName=”1.0“&gt:targetSdkVersion=”23“/&gt:allowBackup=”true“android:icon=”@mipmap/ic_launcher“androi...

PLSQL操作Oracle创建用户和表(含创建用户名和密码)

1》 打开PLSQL,填写用户名和密码,为数据库选择ORCL2,成功登录后可以在界面顶部看到以下信息system@ORCL这意味着用户系统处于登录状态。菜单栏中的会话可以登录和注销。...