MVC4 and page life cycle?

2020-05-24 05:59发布

问题:

ASP.NET MVC4 doesn't have a page life cycle like regular aspx pages do. How does one make use of preinit, init, prerender in MVC4?

Is there any type of life cycle in MVC4?

回答1:

No, there is no page life cycle per se (because there is no 'page' object), but there is a request processing pipeline, which usually goes something like this:

  1. Incoming request is picked up by the System.Web.Routing.UrlRoutingModule which uses the request url to map the request to a controller action method.
  2. The appropriate controller is instantiated
  3. Model binding and input validation may occur
  4. The OnActionExecuting-methods of action filters on the controller and/or action are invoked
  5. The action method itself is invoked
  6. Any OnActionExecuted and OnResultExecuting-methods of action filters are invoked
  7. The ActionResult returned by the action method (typically, a ViewResult which renders HTML) is executed.
  8. Any OnResultExecuted-methods of action filters are invoked.

The list above is just a rough sketch:

Routing: The mapping of an incoming request to the action method of an MVC controller is a story in and of itself. See ASP.NET Routing on MSDN for more info.

Action filters: There are action filters for authorization, output caching, error handling etc., all of which run at a certain time. This time see Filtering in ASP.NET MVC on MSDN for more info.

ASP.NET: And, of course there's still all the traditional ASP.NET application events. Hence, HTTP modules like good old System.Web.Security.FormsAuthenticationModule and System.Web.Caching.OutputCacheModule, may still take part in the processing of a request.

If you want to really delve into the details, download the source code for the ASP.NET web stack from CodePlex. Much of what you are after will be in the System.Web.Mvc.ControllerActionInvoker class, which, despite the scary name, isn't too hard to follow.

See Dejan's answer for a link to a good diagram that sums up much of this.



回答2:

  1. Your web browser sends HTTP Request on server
  2. Request goes through HTTP Routing more info here
  3. These routes are usually listed in Global.asax.cs file, when our request is matched by one of these map routes we are forward on
  4. Route handler, here we create MVC request handler, we now know which controller is will be used and with action to perform
  5. Then we get to controller where we call services and create model
  6. we pass this model to view engine (eg RAzor)
  7. then view is rendered and outputed in Response

Msdn documentation can be found on http://msdn.microsoft.com/en-us/library/dd381612(v=vs.98).aspx



回答3:

You could check this article "Lifecycle of an ASP.NET MVC 5 Application" It's published about a week ago or so. Here is also a PDF file to download.