快速业务通道

Asp.net MVC生命周期

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-05-21

Asp.net应用程序管道处理用户请求时特别强调"时机",对Asp.net生命周期的了解多少直接影响我们写页面和控件的效率。

对于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的配置节:

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

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

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

看到这里我们的第一个问题实际上已经有了答案:时机是在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的时候发生了什么呢?

Request 请求到来

IIS 根据请求特征将处理权移交给 ASP.NET

UrlRoutingModule将当前请求在 Route Table中进行匹配

UrlRoutingModule在RouteCollection中查找Request匹配的RouteHandler,默认是MvcRouteHandler MvcRouteHandler 创建 MvcHandler实例.

MvcHandler执行 ProcessRequest.

MvcHandler 使用 IControllerFactory 获得实现了IController接口的实例,找到对应的HomeController

根据Request触发HomeController的Index方法

Index将执行结果存放在ViewData

HomeController的Index方法返回 ActionResult

Views/Home/Index.aspx将 ViewData呈现在页面上

Index.aspx执行ProcessRequest方法

Index.aspx执行Render方法 输出到客户端

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

public class MvcApplication : System.Web.HttpApplication
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

                //The controller route valu

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号