Asp.net应用程序管道处理用户请求时特别强调"时机",对Asp.net生命周期的了解多少直接影响我们写页面和控件的效率。因此在2007年和2008年我在这个话题上各写了一篇文章:

对于Asp.net MVC,我对它的生命周期还是兴趣很浓,于是提出两个问题:

一个HTTP请求从IIS移交到Asp.net运行时,Asp.net MVC是在什么时机获得了控制权并对请求进行处理呢?处理过程又是怎样的?

以IIS7中asp.net应用程序生命周期为例,下图是来自MSDN的一张HTTP请求处理过程发生事件的简图,后面我列出了一个完整的事件列表。既然Asp.net Mvc还是以Asp.net运行时为基础那么它必然要在Asp.net应用程序的生命周期中对请求进行截获。第一反应当然是去web.config里面去翻翻,我们可以看到UrlRoutingModule的配置节:

  1.       <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

下面要做的就顺理成章了,用Reflector打开这个程序集,可以看到以下代码:

  1. protected virtual void Init(HttpApplication application)  
  2.     {  
  3.         application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);  
  4.         application.PostMapRequestHandler += new EventHandler(this.OnApplicationPostMapRequestHandler);  
  5.     }  

看到这里我们的第一个问题实际上已经有了答案:时机是在PostResolveRequestCache和PostMapRequestHandler.

ResolveRequestCache event
Occurs when ASP.NET finishes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler (for example, a page or an XML Web service).

源文档 <http://msdn.microsoft.com/en-us/library/system.web.httpapplication.resolverequestcache.aspx>

PostMapRequestHandler event
Occurs when ASP.NET has mapped the current request to the appropriate event handler.

源文档 <http://msdn.microsoft.com/en-us/library/system.web.httpapplication.postmaprequesthandler.aspx>

我们使用VS2008中Asp.net Mvc模板创建一个Demo完成后续的讨论,当我们访问/Home的时候发生了什么呢?

  1. Request 请求到来
  2. IIS 根据请求特征将处理权移交给 ASP.NET
  3. UrlRoutingModule将当前请求在 Route Table中进行匹配
  4. UrlRoutingModule在RouteCollection中查找Request匹配的RouteHandler,默认是MvcRouteHandler MvcRouteHandler 创建 MvcHandler实例.
  5.  MvcHandler执行 ProcessRequest.
  6.  MvcHandler 使用 IControllerFactory 获得实现了IController接口的实例,找到对应的HomeController
  7.  根据Request触发HomeController的Index方法
  8. Index将执行结果存放在ViewData
  9. HomeController的Index方法返回 ActionResult
  10. Views/Home/Index.aspx将 ViewData呈现在页面上
  11. Index.aspx执行ProcessRequest方法
  12. Index.aspx执行Render方法 输出到客户端

通过阅读Asp.net Mvc的源码,我们可以得到更为详细的处理过程,我尽可能的忽略掉枝节,强调请求处理的流程.我们从Global.asax.cs文件切入,下面是一段样例代码,这里初始化了路由表,请特别特别注意注释部分:

  1. public class mvcApplication : System.Web.HttpApplication  
  2.      {  
  3.          public static void RegisterRoutes(RouteCollection routes)  
  4.          {  
  5.              routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.               
  7.              //The controller route value is a special value that the System.Web.mvc.mvcHandler class uses to call into the IControllerFactory interface.  
  8.              //The basic route handler is an instance of IRouteHandler named mvcRouteHandler.  
  9.              //We have complete control and could provide our own implementation of IRouteHandler if we wished.  
  10.              routes.MapRoute(  
  11.                  "Default",                                              // Route name  
  12.                  "{controller}/{action}/{id}",                           // URL with parameters  
  13.                  new { controller = "Home", action = "Index", id = "" }  // Parameter defaults  
  14.              );  
  15.             
  16.    
  17.          }  
  18.    
  19.          protected void Application_Start()  
  20.          {  
  21.              RegisterRoutes(RouteTable.Routes);  
  22.          }  

UrlRoutingMoudule在PostResolveRequestCache阶段从RouteCollection中获取当前请求的RouteData.RouteData包含了一个请求处理对应的Controller和Action,RouteData这个作用贯穿请求的处理过程.RouteData中提取RouteHandler,这里默认是MvcRouteHandler,MvcRouteHandler获取HttpHandler,这里默认的是MvcHandler.

  1. PostResolveRequestCache  
  2.     public virtual void PostResolveRequestCache(HttpContextBase context)  
  3. {  
  4.     RouteData routeData = this.RouteCollection.GetRouteData(context);  
  5.     if (routeData != null)  
  6.     {  
  7.         IRouteHandler routeHandler = routeData.RouteHandler;  
  8.         if (routeHandler == null)  
  9.         {  
  10.             throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoRouteHandler, new object[0]));  
  11.         }  
  12.         if (!(routeHandler is StopRoutingHandler))  
  13.         {  
  14.             RequestContext requestContext = new RequestContext(context, routeData);  
  15.             IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);  
  16.             if (httpHandler == null)  
  17.             {  
  18.                 throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoHttpHandler, new object[] { routeHandler.GetType() }));  
  19.             }  
  20.             RequestData data2 = new RequestData();  
  21.             data2.OriginalPath = context.Request.Path;  
  22.             data2.HttpHandler = httpHandler;  
  23.             context.Items[_requestDataKey] = data2;  
  24.             context.RewritePath("~/UrlRouting.axd");  
  25.         }  
  26.     }  
  27. }  

MvcHandler.ProcessRequest()中首先使用HttpContextWrapper对HttpContext进行封装,封装的目的是为了解耦以获得可测试性.然后从RequestContext.RouteData中提取Controller名称.
ControllerBuilder.GetControllerFactory --> ControllerFactory.CreateController --> IController.Execute

ControllerBase实现了IController接口,在Initialize时将RequestContext封装成为ControllerContext,Controller继承自ControllerBase并实现抽象方法ExecuteCore()

在ExecuteCore中,Controller首先从RouteData中获得ActionName,然后执行ActionInvoker.InvokeAction.

在ActionInvoker中我们可以看到各种Filter,这是一种AOP实践:在Action方法执行的前后执行若干方法.这里有四种Filter:ActionFilters,ResultFilters,AuthorizationFilters,ExceptionFilters.这四种Filter并不是封闭的,都有对应的接口,这四个只是默认实现.Filter的执行顺序是:AuthorizationFilter--->Action Filter.OnActionExecuting--->Action Method--->ActionFilter.OnActionExecuted.InvokeActionMethodWithFilters返回的结果是ActionExecutedContext,接下来将Controller执行OnResultExecuting 方法.ActionResult执行的结果可以是ViewResult,JsonResult,RedirectResult,ContentResult,或者是自定义的Result类型.

如果返回的类型是ViewResult,我们先看一下ViewReuslt的继承关系:ViewResult-->ViewResultBase-->ActionResult,ViewResult包含两个属性View和ViewEngineCollection,实际上是包含了两个接口的实现:IViewEngine定义了怎么定位View/Partial View.IView定义了如何RenderView.默认的实现时WebFormView和WebFormViewEngine.

Filter OnResultExecuted 最后一步了,可以这里捕获异常.上面我们说过还有ExceptionFilters,如果前面过程中的异常没有被捕获那么最终都会到冒泡到ExceptionFilters.

  • RouteData中获得ActionName
  • ActionInvoker.InvokeAction
  • 通过ControllerContext获取ControllerDescriptor
  • FindAction-获取ActionDescriptor
  • GetFilters
  • ModelBinder把Request中的数据转换成Action方法需要的参数
  • AuthorizationFilter
  • Action Filter.OnActionExecuting
  • Action
  • ActionFilter.OnActionExecuted
  • ResultFilter.OnResultExecuting
  • ActionResult Execution
  • ResultFilter.OnResultExecuted
  • WebFormViewEngine.CreateView
  • WebFormView.Render
  • ResultFilter.OnExecuted

Asp.net MVC生命周期的更多相关文章

  1. ASP.NET MVC 生命周期

    本文的目的旨在详细描述ASP.NET MVC请求从开始到结束的每一个过程.我希望能理解在浏览器输入URL并敲击回车来请求一个ASP.NET MVC网站的页面之后发生的任何事情. 为什么需要关心这些?有 ...

  2. ASP.NET MVC生命周期介绍(转)

    本文以IIS7中asp.net应用程序生命周期为例,介绍了asp.net mvc的生命周期. asp.net应用程序管道处理用户请求时特别强调"时机",对asp.net生命周期的了 ...

  3. [收藏]Asp.net MVC生命周期

    一个HTTP请求从IIS移交到Asp.net运行时,Asp.net MVC是在什么时机获得了控制权并对请求进行处理呢?处理过程又是怎样的? 以IIS7中asp.net应用程序生命周期为例,下图是来自M ...

  4. 1.3 ASP.NET MVC生命周期

    ASP.NET MVC的执行生命周期主要分为三个阶段,分别是网址路由对比.执行控制器与动作.执行视图并返回结果.从ASP.NET MVC接受HTTP请求到返回HTTP响应的过程如下图所示.

  5. asp.net mvc生命周期学习

    ASP.NET MVC是一个扩展性非常强的框架,探究其生命周期对用Mock框架来模拟某些东西,达到单元测试效果,和开发扩展我们的程序是很好的. 生命周期1:创建routetable.把URL映射到ha ...

  6. ASP.NET MVC生命周期与管道模型

      先来熟悉下asp.net请求管道 1.当客户端发送http://localhost:80/home/index请求时 2.首先到达服务端的内核模块HTTP.SYS(它监听80端口),通过访问注册表 ...

  7. 【深入ASP.NET原理系列】--ASP.NET页面生命周期

    前言 ASP.NET页面运行时候,页面将经历一个生命周期,在生命周期中将执行一系列的处理步骤.包括初始化.实例化控件.还原和维护状态.运行时间处理程序代码以及进行呈现.熟悉页面生命周期非常重要,这样我 ...

  8. 微软Asp.net MVC5生命周期流程图

           .NET WEB Development blog 发布了Asp.net MVC5生命周期文档, 这个文档类似Asp.net应用程序生命周期,您以前开发ASP.NET WEB应用程序应该 ...

  9. MVC学习笔记---MVC生命周期

    Asp.net应用程序管道处理用户请求时特别强调"时机",对Asp.net生命周期的了解多少直接影响我们写页面和控件的效率.因此在2007年和2008年我在这个话题上各写了一篇文章 ...

随机推荐

  1. 02 Linux 下安装JDK并测试开发“Hello World!”

    测试环境 主机系统:Win7 64位 虚拟机:VMware® Workstation 11.1.0 虚拟机系统:CentOS 6.5 64位   Kernel 2.6.32-431.e16.x86_6 ...

  2. windows 代理服务器的搭建,提供Android 端访问公网.

    这段时间遇到一个情况,移动的网络收费.但是可以访问学校内部的网络,比如说学校官网图书馆之类了.所以我这里便想到一个方法,用学校内部一个可以访问互联网的主机充当代理服务器(我这里使用自己的电脑,非服务器 ...

  3. 3、Linux 获取帮助的方法-关机命令-7个系统启动级别

    1.获取帮助的方法: (1).命令 -h 或--help (2).man man 命令  --->/user 查看user选项 /选项 ---->n 查看下一项 2.关机命令 (1).sh ...

  4. Android主流UI开源库整理(转载)

    http://www.jianshu.com/p/47a4a7b99364 标题隐含了两个层面的意思,一个是主流,另一个是UI.主流既通用,一些常规的按钮.Switch.进度条等控件都是通用控件,因此 ...

  5. 关于C++中的类型转换

    C++中定义了四种类型转换操作符:static_cast.const_cast.dynamic_cast和reinterpret_cast. static_cast的用法类似于C语言中的强制类型转换, ...

  6. 计算机视觉:关于视觉算法源码中常出现的imageLib库的使用指南

    1.ReadImage(CImage &im, char* path)/ WriteImage(CImage &im, char* path) (1)将im强制转换为CByteImag ...

  7. C++设计模式-Factory工厂模式

    Factory1.定义创建对象的接口,封装对象的创建2.将实际创建工作延迟到子类中,例如,类A中药使用类B,B是抽象父类,但是在类A中不知道具体要实例化哪一个B的子类,但是在类A的子类D中是可以知道的 ...

  8. php CI ip限制

    public function index() { $ip = $this->input->ip_address(); if(!in_array($ip, $this->allowe ...

  9. Jquery异步上传图片

    网页中这样: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head id=& ...

  10. 基于boa服务器的web控制mini2440的GPIO口

    win7 系统  虚拟机:ubuntu12.04 开发板:mini2440 上一篇已经详细的讲解了如何配置boa服务器,在这里我们就要利用boa服务器带来的便利,利用web控制开发板上的GIPO口,这 ...