Asp.net MVC Request Life Cycle

Asp.net MVC Request Life Cycle

While programming with Asp.net MVC, you should be aware of the life of an Asp.net MVC request from birth to death. In this article, I am going to expose the Asp.net MVC Request Life cycle. There are seven main steps that happen when you make a request to an Asp.net MVC web applications. For more details refer Detailed ASP.NET MVC Pipeline

  1. Routing

    Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the request’s URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. The default one calls the MvcHandler. The routing engine returns a 404 HTTP status code against that request if the patterns is not found in the Route Table.

    When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.

    1. public static void RegisterRoutes(RouteCollection routes)
    2. {
    3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    4. routes.MapRoute( "Default", // Route name
    5. "{controller}/{action}/{id}", // URL with parameters
    6. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    7. );
    8. }
  2. MvcHandler

    The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method as shown below:

    1. protected internal virtual void ProcessRequest(HttpContextBase httpContext)
    2. {
    3. SecurityUtil.ProcessInApplicationTrust(delegate {
    4. IController controller;
    5. IControllerFactory factory;
    6. this.ProcessRequestInit(httpContext, out controller, out factory);
    7. try
    8. {
    9. controller.Execute(this.RequestContext);
    10. }
    11. finally
    12. {
    13. factory.ReleaseController(controller);
    14. }
    15. });
    16. }
  3. Controller

    As shown in above code, MvcHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, the Execute method is called. The IControllerFactory could be the default controller factory or a custom factory initialized at the Application_Start event, as shown below:

    1. protected void Application_Start()
    2. {
    3. AreaRegistration.RegisterAllAreas();
    4. RegisterRoutes(RouteTable.Routes);
    5. ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
    6. }
  4. Action Execution

    Once the controller has been instantiated, Controller‘s ActionInvoker determines which specific action to invoke on the controller. Action to be execute is chosen based on attributes ActionNameSelectorAttribute (by default method which have the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than one method found, the correct one is chosen with the help of this attribute).

  5. View Result

    The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

  6. View Engine

    The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by IViewEngine interface of the view engine. By default Asp.Net MVC usesWebForm and Razor view engines. You can also register your own custom view engine to your Asp.Net MVC application as shown below:

    1. protected void Application_Start()
    2. {
    3. //Remove All View Engine including Webform and Razor
    4. ViewEngines.Engines.Clear();
    5. //Register Your Custom View Engine
    6. ViewEngines.Engines.Add(new CustomViewEngine());
    7. //Other code is removed for clarity
    8. }
  7. View

    Action method may returns a text string,a binary file or a Json formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.

What do you think?

I hope you will enjoy the Asp.Net MVC request life cycle while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

时间: 2024-07-31 18:32:51

Asp.net MVC Request Life Cycle的相关文章

Asp.net MVC 3 防止 Cross-Site Request Forgery (CSRF)原理及扩展

原理:http://blog.csdn.net/cpytiger/article/details/8781457 原文地址:http://www.cnblogs.com/wintersun/archive/2011/12/09/2282675.html Cross-Site Request Forgery (CSRF) 是我们Web站点中常见的安全隐患. 下面我们在Asp.net MVC3 来演示一下. 例如我们有一个HomeContoller中一个Submit Action,我们标记了Http

解决ASP.NET MVC(post数据)Json请求太大,无法反序列化(The JSON request was too large to be deserialized)

这个问题出现的场景并不是很多,当你向服务端异步(ajax)post数据非常大的情况下(比如做权限管理的时候给某个角色分配权限那么就可能会出现,我所遇到的就是该角色大概200个模块每个模块平均2个功能----那么发送到服务端action的将是一个有着400个对象的数组) 之前我们向服务端异步post数组可能需要使用 1 $.ajax({ 2 type: 'POST', 3 url: '/system/SaveRoleReModule', 4 dataType: "json", 5 con

ASP.NET MVC 复制MVC项目代码到同一个项目的时候报错The request for ‘home’ has found the following matching controll

ASP.NET MVC 复制MVC项目代码到同一个项目的时候报错The request for 'home' has found the following matching controll "/"应用程序中的服务器错误. Multiple types were found that match the controller named 'home'. This can happen if the route that services this request ('{control

asp.net mvc 客户端(&)中检测到有潜在危险的 Request.Path 值。

出现这个错误后,试过 <pages validateRequest="false"> <httpRuntime requestValidationMode="2.0"/> [ValidateInput(false)] 都不ok,经测试只用以下配置就ok了 <httpRuntime requestPathInvalidCharacters="" /> MSDN解释:在请求路径中无效的字符的列表以逗号分隔). 以下

Demystifying ASP.NET MVC 5 Error Pages and Error Logging

出处:http://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging Error pages and error logging, both so elementary and yet so complex in ASP.NET MVC. Perhaps complex is not entirely true, but it is certainly not very straight forward fo

ASP.NET MVC - 路由系统

ASP.NET MVC的请求URL不再对应于传统ASP.NET程序的ASPX文件物理地址,而是把请求映射到一个控制器(Controller)类的方法(Action)上,Controller.Action再加上参数构成ASP.Net MVC请求的Url.下面我们来看下路由系统的主要对象. UrlRoutingModule ASP.NET MVC框架的路由实质是从传统ASP.NET管道扩展HttpModule而来,这个模块正是UrlRoutingModule.通过反编译可以看到UrlRoutingM

ASP.NET MVC框架下添加菜单栏及分页项目

原创声明:本文为作者原创,转载请注明出处:http://www.cnblogs.com/DrizzleWorm/p/7274866.html ,谢谢! 我是做前端开发的,之前用C#的三层架构(UI.BLL.DAL)做过一个网站,这是我第一次接触ASP.NET MVC框架,首先给大家分享别人整理的ASP.NET MVC框架的一组教程:http://www.cnblogs.com/powertoolsteam/archive/2015/08/13/4667892.html内容很齐全,我是在先看了其他

asp.net MVC 常见安全问题及解决方案

asp.net MVC 常见安全问题及解决方案 一.CSRF (Cross-site request forgery跨站请求伪造,也被称为"one click attack"或者session riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用) 详细说明: http://imroot.diandian.com/post/2010-11-21/40031442584 Example :            在登陆状态下进入了攻击网站向安全站点发送了请求. Solut

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W