技术开发 频道

ASP.NET:细说Request与Request.Params

  实现方式分析

  前面的示例中,我演示了在访问Request[]与Request.Params[] 时得到了不同的结果。为什么会有不同的结果呢,我想我们还是先去看一下微软在.net framework中的实现吧。

  首先,我们来看一下Request[]的实现,它是一个默认的索引器,实现代码如下:

public string this[string key]
{
    
get
    {
        
string str = this.QueryString[key];
        
if( str != null ) {
            
return str;
        }
        
str = this.Form[key];
        
if( str != null ) {
            
return str;
        }
        HttpCookie cookie
= this.Cookies[key];
        
if( cookie != null ) {
            
return cookie.Value;
        }
        
str = this.ServerVariables[key];
        
if( str != null ) {
            
return str;
        }
        
return null;
    }
}

   这段代码的意思是:根据指定的key,依次访问QueryString,Form,Cookies,ServerVariables这4个集合,如果在任意一个集合中找到了,就立即返回。

  Request.Params[]的实现如下:

public NameValueCollection Params
{
    
get
    {
        
//if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low))
        
//{
        
//    return this.GetParams();
        
//}
        
//return this.GetParamsWithDemand();

        
// 为了便于理解,我注释了上面的代码,其实关键还是下面的调用。
        
return this.GetParams();
    }
}
private NameValueCollection GetParams()
{
    
if( this._params == null ) {
        this._params
= new HttpValueCollection(0x40);
        this.FillInParamsCollection();
        this._params.MakeReadOnly();
    }
    
return this._params;
}
private void FillInParamsCollection()
{
    this._params.Add(this.QueryString);
    this._params.Add(this.Form);
    this._params.Add(this.Cookies);
    this._params.Add(this.ServerVariables);
}

   它的实现方式是:先判断_params这个Field成员是否为null,如果是,则创建一个集合,并把QueryString,Form,Cookies,ServerVariables这4个集合的数据全部填充进来,以后的查询都直接在这个集合中进行。

  我们可以看到,这是二个截然不同的实现方式。也就是因为这个原因,在某些特殊情况下访问它们得到的结果将会不一样。

  不一样的原因是:Request.Params[]创建了一个新集合,并合并了这4个数据源,遇到同名的key,自然结果就会不同了。

  再谈Cookie

  在博客【我心目中的Asp.net核心对象】中,说到Request.Params[]时,我简单地说了一句:而且更糟糕的是写Cookie后,也会更新集合。 如何理解这句话呢?

  我想我们还是来看一下我们是如何写一个Cookie,并发送到客户端的吧。下面我就COPY一段 【细说Coookie】中的一段原文吧:

0
相关文章