HttpRequest的QueryString属性 的一点认识_实用技巧

如:

当然我们一般都是按照提示来把framework版本设置2.0来解决。为什么可以这么解决了,还有没有其它的解决方法了。
先让我们看看QueryString的源代码吧:

复制代码 代码如下:

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);
this.ValidateNameValueCollection(this._queryString, RequestValidationSource.QueryString);
}
return this._queryString;
}
}
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))
{
this._queryString.FillFromString(this.QueryStringText, true, this.QueryStringEncoding);
}
}

  先让我们插入一点 那就是QueryString默认已经做了url解码。 其中HttpValueCollection的 FillFromEncodedBytes方法如下

复制代码 代码如下:

internal void FillFromEncodedBytes(byte[] bytes, Encoding encoding)
{
int num = (bytes != null) ? bytes.Length : 0;
for (int i = 0; i < num; i++)
{
string str;
string str2;
this.ThrowIfMaxHttpCollectionKeysExceeded();
int offset = i;
int num4 = -1;
while (i < num)
{
byte num5 = bytes[i];
if (num5 == 0x3d)
{
if (num4 < 0)
{
num4 = i;
}
}
else if (num5 == 0x26)
{
break;
}
i++;
}
if (num4 >= 0)
{
str = HttpUtility.UrlDecode(bytes, offset, num4 - offset, encoding);
str2 = HttpUtility.UrlDecode(bytes, num4 + 1, (i - num4) - 1, encoding);
}
else
{
str = null;
str2 = HttpUtility.UrlDecode(bytes, offset, i - offset, encoding);
}
base.Add(str, str2);
if ((i == (num - 1)) && (bytes[i] == 0x26))
{
base.Add(null, string.Empty);
}
}
}

从这里我们可以看到QueryString已经为我们做了解码工作,我们不需要写成 HttpUtility.HtmlDecode(Request.QueryString["xxx"])而是直接写成Request.QueryString["xxx"]就ok了。
现在让我们来看看你QueryString的验证,在代码中有

复制代码 代码如下:

if (this._flags[1])
{
this._flags.Clear(1);
this.ValidateNameValueCollection(this._queryString, RequestValidationSource.QueryString);
}

一看this.ValidateNameValueCollection这个方法名称就知道是干什么的了,验证QueryString数据;那么在什么情况下验证的了?
让我们看看this._flags[1]在什么地方设置的:

复制代码 代码如下:

public void ValidateInput()
{
if (!this._flags[0x8000])
{
this._flags.Set(0x8000);
this._flags.Set(1);
this._flags.Set(2);
this._flags.Set(4);
this._flags.Set(0x40);
this._flags.Set(0x80);
this._flags.Set(0x100);
this._flags.Set(0x200);
this._flags.Set(8);
}
}

  而该方法在ValidateInputIfRequiredByConfig中调用,调用代码

复制代码 代码如下:

internal void ValidateInputIfRequiredByConfig()
{
.........
if (httpRuntime.RequestValidationMode >= VersionUtil.Framework40)
{
this.ValidateInput();
}
}

我想现在大家都应该明白为什么错题提示让我们把framework改为2.0了吧。应为在4.0后才验证。这种解决问题的方法是关闭验证,那么我们是否可以改变默认的验证规则了?
让我们看看ValidateNameValueCollection

复制代码 代码如下:

private void ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection)
{
int count = nvc.Count;
for (int i = 0; i < count; i++)
{
string key = nvc.GetKey(i);
if ((key == null) || !key.StartsWith("__", StringComparison.Ordinal))
{
string str2 = nvc.Get(i);
if (!string.IsNullOrEmpty(str2))
{
this.ValidateString(str2, key, requestCollection);
}
}
}
}
private void ValidateString(string value, string collectionKey, RequestValidationSource requestCollection)
{
int num;
value = RemoveNullCharacters(value);
if (!RequestValidator.Current.IsValidRequestString(this.Context, value, requestCollection, collectionKey, out num))
{
string str = collectionKey + "=\"";
int startIndex = num - 10;
if (startIndex <= 0)
{
startIndex = 0;
}
else
{
str = str + "...";
}
int length = num + 20;
if (length >= value.Length)
{
length = value.Length;
str = str + value.Substring(startIndex, length - startIndex) + "\"";
}
else
{
str = str + value.Substring(startIndex, length - startIndex) + "...\"";
}
string requestValidationSourceName = GetRequestValidationSourceName(requestCollection);
throw new HttpRequestValidationException(SR.GetString("Dangerous_input_detected", new object[] { requestValidationSourceName, str }));
}
}

  
  哦?原来一切都明白了,验证是在RequestValidator做的。

复制代码 代码如下:

public class RequestValidator
{
// Fields
private static RequestValidator _customValidator;
private static readonly Lazy<RequestValidator> _customValidatorResolver = new Lazy<RequestValidator>(new Func<RequestValidator>(RequestValidator.GetCustomValidatorFromConfig));
// Methods
private static RequestValidator GetCustomValidatorFromConfig()
{
HttpRuntimeSection httpRuntime = RuntimeConfig.GetAppConfig().HttpRuntime;
Type userBaseType = ConfigUtil.GetType(httpRuntime.RequestValidationType, "requestValidationType", httpRuntime);
ConfigUtil.CheckBaseType(typeof(RequestValidator), userBaseType, "requestValidationType", httpRuntime);
return (RequestValidator) HttpRuntime.CreatePublicInstance(userBaseType);
}
internal static void InitializeOnFirstRequest()
{
RequestValidator local1 = _customValidatorResolver.Value;
}
private static bool IsAtoZ(char c)
{
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}
protected internal virtual bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
if (requestValidationSource == RequestValidationSource.Headers)
{
validationFailureIndex = 0;
return true;
}
return !CrossSiteScriptingValidation.IsDangerousString(value, out validationFailureIndex);
}
// Properties
public static RequestValidator Current
{
get
{
if (_customValidator == null)
{
_customValidator = _customValidatorResolver.Value;
}
return _customValidator;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_customValidator = value;
}
}
} 

主要的验证方法还是在CrossSiteScriptingValidation.IsDangerousString(value, out validationFailureIndex);而CrossSiteScriptingValidation是一个内部类,无法修改。
让我们看看CrossSiteScriptingValidation类大代码把

复制代码 代码如下:

internal static class CrossSiteScriptingValidation
{
// Fields
private static char[] startingChars = new char[] { '<', '&' };
// Methods
private static bool IsAtoZ(char c)
{
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}
internal static bool IsDangerousString(string s, out int matchIndex)
{
matchIndex = 0;
int startIndex = 0;
while (true)
{
int num2 = s.IndexOfAny(startingChars, startIndex);
if (num2 < 0)
{
return false;
}
if (num2 == (s.Length - 1))
{
return false;
}
matchIndex = num2;
char ch = s[num2];
if (ch != '&')
{
if ((ch == '<') && ((IsAtoZ(s[num2 + 1]) || (s[num2 + 1] == '!')) || ((s[num2 + 1] == '/') || (s[num2 + 1] == '?'))))
{
return true;
}
}
else if (s[num2 + 1] == '#')
{
return true;
}
startIndex = num2 + 1;
}
}
internal static bool IsDangerousUrl(string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
s = s.Trim();
int length = s.Length;
if (((((length > 4) && ((s[0] == 'h') || (s[0] == 'H'))) && ((s[1] == 't') || (s[1] == 'T'))) && (((s[2] == 't') || (s[2] == 'T')) && ((s[3] == 'p') || (s[3] == 'P')))) && ((s[4] == ':') || (((length > 5) && ((s[4] == 's') || (s[4] == 'S'))) && (s[5] == ':'))))
{
return false;
}
if (s.IndexOf(':') == -1)
{
return false;
}
return true;
}
internal static bool IsValidJavascriptId(string id)
{
if (!string.IsNullOrEmpty(id))
{
return CodeGenerator.IsValidLanguageIndependentIdentifier(id);
}
return true;
}
}

  结果我们发现 <! </ <? <[a-zA-z] 这些情况验证都是通不过的。
所以我们只需要重写RequestValidator就可以了。
例如我们现在需要处理我们现在需要过滤QueryString中k=&...的情况

复制代码 代码如下:

public class CustRequestValidator : RequestValidator
{
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
validationFailureIndex = 0;
//我们现在需要过滤QueryString中k=&...的情况
if (requestValidationSource == RequestValidationSource.QueryString&&collectionKey.Equals("k")&& value.StartsWith("&"))
{
return true;
}
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
  <httpRuntime requestValidationType="MvcApp.CustRequestValidator"/>

个人在这里只是提供一个思想,欢迎大家拍砖!

时间: 2024-08-06 19:51:35

HttpRequest的QueryString属性 的一点认识_实用技巧的相关文章

XML文件修改节点属性值(多种方法)_实用技巧

xml 文件内容: 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?> <subtitles> <info> <content>最新通告:五一放假七天!请各教员悉知</content> <speed>4</speed> <color>red</color> </info> </subtitles

Equals和==的区别 公共变量和属性的区别小结_实用技巧

Equals 和==的区别 C#中有两种不同的相等:引用相等和值相等 == 是比较两个变量的值是否相同或两个引用是不是指向同一个内存地址. Equals()方法是比较两个对象指向内存空间里的内容是不是相同.也就是比较两个"引用类型" 是否是对同一对象的引用,即两个对象的内容是否相同. 公共变量和属性的区别 变量对于类本身而言,称为域. 属性是类的外部显示出来的特性,只是公开属性,如何进行赋值(set)和如何进行取值(get)都进行了封装,对于类外部是不可见的.对于外部使用者来说只能够使

ASP.NET中控件的EnableViewState属性及彻底禁用_实用技巧

在ASP.Net中对各个WebForm控件引入以前没有的EnableViewState属性.这个属性究竟有什么用.我们知道对于WebForm而言,其代码是在服务器端的,以处理客户端的请求.当用户通过浏览器浏览网页的时候,会对网页进行某些操作,比如打开新链接,或单击某个按钮.在ASP中,这些是通过脚本语言对其进行处理,之后再传递给服务器端.但是在ASP.NET下,由于采用了code behind技术,在coding的时候,通常是将以前客户端完成的工作放到了服务器端. 那么,服务器是怎么知道客户的操

ASP.NET单选按钮控件RadioButton常用属性和方法介绍_实用技巧

1.常用属性: (1)Checked属性:用来设置或返回单选按钮是否被选中,选中时值为true,没有选中时值为false. (2)AutoCheck 属性:如果 AutoCheck 属性被设置为 true(默认),那么当选择该单选按钮时,将自动清除该组中所有其他单选按钮.对一般用户来说,不需改变该属性,采用默认值(true)即可. (3)Appearance 属性:用来获取或设置单选按钮控件的外观.当其取值为 Appearance.Button 时,将使单选按钮的外观像命令按钮一样:当选定它时,

ASP与ASP.NET互通COOKIES的一点经验_实用技巧

  在微软推出.NET并进行了大规模的推广普及之后,ASP.NET逐渐进入了信息化系统开发的主流.但与此同时,而用ASP开发的旧系统面则临被整合,这时,面临一个问题:ASP与ASP.NET互相整合时,其中文COOKIES信息无法被互通共享,当使用ASP.NET写入中文COOKIES信息后,使用ASP进行读取,读出来的却是乱码,而非中文.    后来通过查找资料,不停地实践,终于找到了问题的根源,中文COOKIES信息在ASP中无法被正确读取得原因为其中文编码格式不同.    开发项目Web.co

Request.RawUrl 属性的应用收_实用技巧

原始 URL 定义为 URL 中域信息之后的部分.在 URL 字符串 http://www.contoso.com/articles/recent.aspx 中,原始 URL 为 /articles/recent.aspx.原始 URL 包括查询字符串(如果存在). 复制代码 代码如下: if (Request.RawUrl.ToLowerInvariant().Contains("/category/")) { DisplayCategories(); } 用来对字符串分析,有选择的

Asp.net cookie的处理流程深入分析_实用技巧

一说到Cookie我想大家都应该知道它是一个保存在客户端,当浏览器请求一个url时,浏览器会携带相关的Cookie达到服务器端,所以服务器是可以操作Cookie的,在Response时,会把Cookie信息输出到客服端.下面我们来看一个demo吧,代码如下: 第一次请求结果如下: 第二次请求结果如下: 到这里我们可以看到第二次请求传入的Cookie正好是第一次请求返回的Cookie信息,这里的cookie信息的维护主要是我们客户端的浏览器,但是在Asp.net程序开发时,Cookie往往是在服务

Win 2000下ASP.NET开发环境的配置_实用技巧

Win 2000下ASP.NET的配置 Win 2000(包括Professional,Server和Advanced Server)在默认情况下是不支持ASP.NET的.必须对它进行一个环境的配置. 客户端 SQL Server .NET 数据提供程序 Microsoft 数据访问组件 (MDAC) 2.6 或更高版本 对系统管理信息的访问 Windows Management Instrumentation (WMI)(在 Windows 2000操作系统一起安装)COM+ 服务 Windo

ASP.NET 控件开发系列之图片切换web控件_实用技巧

开发系列之图片切换web控件_实用技巧-">贴出来控件页面的代码. PicList.ascx 复制代码 代码如下: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="PicList.ascx.cs" Inherits="WebParts_PicList" %> <style type="text/css"&