当前位置: 移动技术网 > IT编程>开发语言>.net > 请求如何进入ASP.NET MVC框架

请求如何进入ASP.NET MVC框架

2017年12月12日  | 移动技术网IT编程  | 我要评论

一、前言

  对于webform开发,请求通常是一个以.aspx结尾的url,对应一个物理文件,从代码的角度来说它其实是一个控件(page)。而在mvc中,一个请求对应的是一个controller里的action。熟悉asp.net的朋友都知道,asp.net请求实际都是交给httphandler处理(实现了ihttphandler的类型)。无论是.aspx,.ashx,.asmx 还是mvc里的action,请求都会交给httphandler。具体是在管道事件中,会根据请求创建一个httphandler,并执行它的pr方法。对于aspx和ashx都很好理解,因为它们本身就实现了ihttphandler接口,而mvc的controller和action都和httphandler没有关系,它是如何实现的呢?接下来我们就看一个请求是如何进入mvc框架内部的。

二、例子

  webform和mvc都是建立在asp.net平台上的,webform出现得比较早,那么mvc是如何做到在不影响底层框架,实现扩展的呢?这主要得益于asp.net的路由机制。路由机制并不属于mvc,webform也可以使用它。它的目的是让一个请求与物理文件分离,原理是通过映射关系,将请求映射到指定的httphandler。例如我们也可以将一个/admin/user.aspx?name=张三 的请求映射成可读性更好的/admin/张三。下面是两种url的注册方式:

public static void registerroutes(routecollection routes)
{
  //mvc
  routes.maproute(
    name: "default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "home", action = "index", id = urlparameter.optional }
  );
 
  //webform
  routes.mappageroute(
    routename: "webform",
    routeurl: "admin/{user}",
    physicalfile: "~/admin/user.aspx"
  );
}

  routecollection是一个route集合,route封装了名称、url模式、约束条件、默认值等路由相关信息。其中,mappageroute是routecollection定义的方法,而maproute是mvc扩展出来的(扩展方法的好处就是可以在不修改原有代码的情况下添加所需的功能)。它们的目的都是一样的,创建一个route对象,添加到集合当中;我们也可以new 一个route对象,然后调用routecollection.add,效果是一样的。下面我们主要关注mvc的实现过程,webform其实也是类似的。

三、分析源码

  接下来我们看mvc是如何利用路由机制实现扩展的。路由机制是通过一个urlroutingmodule完成的,它是一个实现了ihttpmodule的类,路由模块已经默认帮我们注册好了。httpmodule通过注册httpapplication事件参与到管道处理请求中,具体是订阅httpapplication某个阶段的事件。路由机制就是利用这个原理,urlroutingmodule订阅了postresolverequestcache 事件,实现url的映射。为什么是该事件呢?因为该事件的下一步就要完成请求和物理文件的映射,所以必须要此之前进行拦截。核心代码如下:

public class urlroutingmodule : ihttpmodule {
  public routecollection routecollection {
    get {
      if (_routecollection == null) {
        //全局的routecollection集合
        _routecollection = routetable.routes;
      }
      return _routecollection;
    }
    set {
      _routecollection = value;
    }
  }
 
  protected virtual void init(httpapplication application) {
    //注册postresolverequestcache事件
    application.postresolverequestcache += onapplicationpostresolverequestcache;
  }
 
  private void onapplicationpostresolverequestcache(object sender, eventargs e) {
    //创建上下文
    httpapplication app = (httpapplication)sender;
    httpcontextbase context = new httpcontextwrapper(app.context);
    postresolverequestcache(context);
  }
 
  public virtual void postresolverequestcache(httpcontextbase context) {
    //1.获取routedata
    routedata routedata = routecollection.getroutedata(context);
    if (routedata == null) {
      return;
    }
    //2.获取iroutehandler
    iroutehandler routehandler = routedata.routehandler;
    if (routehandler == null) {
       
    }
     
    //requestcontext保证了httpcontext和routedata,在后续使用
    requestcontext requestcontext = new requestcontext(context, routedata);
 
    context.request.requestcontext = requestcontext;
 
    //3.获取ihttphandler
    ihttphandler httphandler = routehandler.gethttphandler(requestcontext);
 
    //重新映射到处理程序
    context.remaphandler(httphandler);
  }
}  

  我们关注主要方法postresolverequestcache,这里有三个关键步骤。

步骤一. 获取routedata

  routedata是对route的包装,在后续的处理中使用。它的获取是通过routecollection获得的,这个和上面注册用到的routetable.routes是同一个集合对象。调用routecollection的getroutedata会遍历它的每一个项,也就是route对象,然后调用route对象的getroutedata方法(mvc内部很多集合都用到了这种设计)。如下代码:

public routedata getroutedata(httpcontextbase httpcontext) {
  using (getreadlock()) {
    foreach (routebase route in this) {
      routedata routedata = route.getroutedata(httpcontext);
      if (routedata != null) {           
        return routedata;
      }
    }
  }
  return null;
}

  route对象的getroutedata方法如下:

public override routedata getroutedata(httpcontextbase httpcontext) {
  string requestpath = httpcontext.request.apprelativecurrentexecutionfilepath.substring(2) + httpcontext.request.pathinfo;
 
  //结合默认值,匹配url
  routevaluedictionary values = _parsedroute.match(requestpath, defaults);
 
  if (values == null) {
    return null;
  }
 
  //包装成routedata,这里为什么不放在if后面呢?
  routedata routedata = new routedata(this, routehandler);
 
  //匹配约束
  if (!processconstraints(httpcontext, values, routedirection.incomingrequest)) {
    return null;
  }
 
  //routedata的values和datatokens都来自于route
  foreach (var value in values) {
    routedata.values.add(value.key, value.value);
  }
  if (datatokens != null) {
    foreach (var prop in datatokens) {
      routedata.datatokens[prop.key] = prop.value;
    }
  }
 
  return routedata;
}

  可以看到,route对象的getroutedata方法会匹配url模式,和检查约束条件,如何不符合会返回null。如果匹配,则new一个routedata。

步骤二、获取iroutehandler接口对象

  上面创建routedata,参数分别是当前route对象和它的routehandler属性。routehandler是一个iroutehandler,这是一个重要接口,它的定义如下:

public interface iroutehandler {
  ihttphandler gethttphandler(requestcontext requestcontext);
}

  很明显,它是用于获取ihttphandler的。那么route对象的routehandler属性又是在哪里初始化的呢?我们回到开始的注册方法,routes.maproute,这个方法根据传递的参数创建一个route对象,该方法的实现如下:

public static route maproute(this routecollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
{
  //创建一个route对象,它的iroutehandler为mvcroutehandler
  route route = new route(url, new mvcroutehandler())
  {
    defaults = createroutevaluedictionary(defaults),
    constraints = createroutevaluedictionary(constraints),
    datatokens = new routevaluedictionary()
  };
 
  if ((namespaces != null) && (namespaces.length > 0))
  {
    route.datatokens["namespaces"] = namespaces;
  }
 
  //将route注册到routecollection中
  routes.add(name, route);
 
  return route;
}

  在创建route时,除了传递url模式外,还默认帮我们传递了一个mvcroutehandler,它实现了iroutehandler接口。
步骤三、获取ihttphandler接口对象

  有了mvcroutehandler,就可以调用它的gethttphandler方法获取ihttphandler了,该方法实现如下:

protected virtual ihttphandler gethttphandler(requestcontext requestcontext)
{
  //设置session状态
  requestcontext.httpcontext.setsessionstatebehavior(getsessionstatebehavior(requestcontext));
 
  //返回一个实现了ihttphandler的mvchandler
  return new mvchandler(requestcontext);
}

  可以看到,它返回了一个mvchandler,mvchandler就实现了ihttphandler接口。所以开头说的,请求本质都是交给httphandler的,其实mvc也是这样的,请求交给了mvchandler处理。我们可以看mvchandler定义和主要方法:

public class mvchandler : ihttpasynchandler, ihttphandler, irequiressessionstate
{
   protected internal virtual iasyncresult beginprocessrequest(httpcontextbase httpcontext, asynccallback callback, object state)
  {
    icontroller controller;
    icontrollerfactory factory;
 
    //这个方法里会激活controller对象
    processrequestinit(httpcontext, out controller, out factory);
 
    iasynccontroller asynccontroller = controller as iasynccontroller;
    if (asynccontroller != null)
    {
      // asynchronous controller
      begininvokedelegate begindelegate = delegate(asynccallback asynccallback, object asyncstate)
      {
        try
        {
          //调用controller的beginexecute方法
          return asynccontroller.beginexecute(requestcontext, asynccallback, asyncstate);
        }
        catch
        {
          factory.releasecontroller(asynccontroller);
          throw;
        }
      };
 
      endinvokedelegate enddelegate = delegate(iasyncresult asyncresult)
      {
        try
        {
          asynccontroller.endexecute(asyncresult);
        }
        finally
        {
          factory.releasecontroller(asynccontroller);
        }
      };
 
      synchronizationcontext synccontext = synchronizationcontextutil.getsynchronizationcontext();
      asynccallback newcallback = asyncutil.wrapcallbackforsynchronizedexecution(callback, synccontext);
      return asyncresultwrapper.begin(newcallback, state, begindelegate, enddelegate, _processrequesttag);
    }
    else
    {
      // synchronous controller
      action action = delegate
      {
        try
        {
          controller.execute(requestcontext);
        }
        finally
        {
          factory.releasecontroller(controller);
        }
      };
 
      return asyncresultwrapper.beginsynchronous(callback, state, action, _processrequesttag);
    }
  }
}

  可以看到,mvchandler的任务就是激活controller,并执行它的execute方法。这个过程和webform里的页面处理是很相似的,.aspx请求到来,会根据虚拟路径找到实现ihttphandler的page(类似于路由机制根据url模式找到mvchandler),然后进入page的页面周期(类似于mvc的激活controller,然后执行action过程)。

四、总结

接下来,简单总结一下请求进入到mvc框架的过程:

1.添加路由对象route到全局的routecollection,route的iroutehandler初始化为mvcroutehandler。

2. urlroutingmodule注册 httpapplication postresolverequestcache事件,实现请求拦截。
3. 请求到来, 在处理事件中遍历routecollection,调用每一个route对象的getroutedata获取routedata包装对象。

4. 调用mvcroutehandler的gethttphandler获取mvchandler。

5. 调用httpcontext的remaphandler将请求映射到mvchandler处理程序。

6. 执行mvchandler的pr方法,激活controller,执行action。

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网