淺析ASP.NET MVC生命周期
我對ASP.NET MVC生命周期還是興趣很濃,于是提出兩個問題:
一個HTTP請求從IIS移交到ASP.NET運(yùn)行時,ASP.NETMVC是在什么時機(jī)獲得了控制權(quán)并對請求進(jìn)行處理呢?處理過程又是怎樣的?
以IIS7中ASP.NET MVC生命周期為例,來自MSDN的一張HTTP請求處理過程發(fā)生事件的簡圖,后面我列出了一個完整的事件列表。既然ASP.NET MVC還是以ASP.NET運(yùn)行時為基礎(chǔ)那么它必然要在ASP.NET MVC生命周期中對請求進(jìn)行截獲。***反應(yīng)當(dāng)然是去web.config里面去翻翻,我們可以看到UrlRoutingModule的配置節(jié):
- <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.
Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
看到這里我們的***個問題實際上已經(jīng)有了答案:時機(jī)是在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).
源文檔
PostMapRequestHandler event
Occurs when ASP.NET has mapped the current request to the appropriate event handler.
源文檔
我們使用VS2008中ASP.NET Mvc模板創(chuàng)建一個Demo完成后續(xù)的討論,當(dāng)我們訪問/Home的時候發(fā)生了什么呢?
1.Request 請求到來
2.IIS 根據(jù)請求特征將處理權(quán)移交給 ASP.NET
3.UrlRoutingModule將當(dāng)前請求在 Route Table中進(jìn)行匹配
4.UrlRoutingModule在RouteCollection中查找Request匹配的RouteHandler,默認(rèn)是MvcRouteHandler MvcRouteHandler 創(chuàng)建 MvcHandler實例.
5.MvcHandler執(zhí)行 ProcessRequest.
6.MvcHandler 使用 IControllerFactory 獲得實現(xiàn)了IController接口的實例,找到對應(yīng)的HomeController
7.根據(jù)Request觸發(fā)HomeController的Index方法
8.Index將執(zhí)行結(jié)果存放在ViewData
9.HomeController的Index方法返回 ActionResult
10.Views/Home/Index.aspx將 ViewData呈現(xiàn)在頁面上
11.Index.aspx執(zhí)行ProcessRequest方法
12.Index.aspx執(zhí)行Render方法 輸出到客戶端
通過閱讀ASP.NET Mvc的源碼,我們可以得到更為詳細(xì)的處理過程,我盡可能的忽略掉枝節(jié),強(qiáng)調(diào)請求處理的流程.我們從Global.asax.cs文件切入。
【編輯推薦】