Net/asp.net MVC Controller controllers (I: In-depth analysis of how the Controller operates)

Source: Internet
Author: User

Read the catalogue:

    • 1. Introduction

    • Ingress of the 2.ASP.NETMVC controller controllers (execution flow of director)

    • 3.ASP.NETMVC Controller's entry (System of Controllers inheritance)

    • 4.ASP.NETMVC IController Factory Controllers factory (controller creation)

1 "Introduction

After the previous article . Net/asp.net routing Routing (in-depth analysis of the routing system Architecture principle) , We have a basic understanding of the entire operating mechanism of the asp.netrouting routing system, and when we can clearly understand how the URL is parsed into a Routedata object, here's how these routing data are used by the application framework behind it, and the portal to the application framework is Mvcroutehandler object;

This article will continue to explain how ASP.NETMVC controller controllers are loaded, activated, and executed after routing, and the set of object models associated with the controller is called by the Mvchandler object as the source, i.e., when we pass After UrlRoutingModule the object, and successfully obtains the routing data to the application framework configuration, the following will enter the IHttpHandler interface, and this interface is really the application framework portal that we set when we initialize the Routedata object, ASP. The NETMVC is used by Mvchandler objects;

The Mvcroutehandler object is a connector for urlroutingmodule and Mvchandler objects, and only after the Mvcroutehandler object is successfully executed. The party can enter into the Mvchandler object, and all subsequent operations can be carried out smoothly;

2 "Ingress of ASP.NETMVC controller controllers (execution flow of the director)

When the system was just started, that is, in the Global.asax.cs file We configured the HTTP client Request Server URL template, in the Route parsing module (urlroutingmodule), it will be through the string-level operation, Parse the placeholder variables for {controller}/{action} in our URL template; So this time the Controller concept is just a string for us, and to the current controller to resolve the position in fact, and the route is basically no matter, because we went through the routing module to the controller to resolve the link Controller parsing is already within the scope of the ASP.NETMVC application framework, and we can simply consider the process of routing parsing (urlroutingmodule) as the process of matching the requested URL (the URL containing the data) with the URL template we configured, to derive the matching URL data (R Outedata), and then encapsulates the URL data together with the current request context into a RequestContext object (Routedata, httpcontextbase) into the controller parsing link, That is Mvchandler, as the parameter of the Mvchandler constructor;

When Mvchandler takes over control, it needs to be prepared to parse and execute the controller, but the controller has a simple object, it has a complex inheritance system and usage, because it needs to coordinate the work of many aspects, so it becomes very complicated;

According to the MVC Architecture model theory, it is known that controller is the intermediate link between model and view, it is necessary to manage the execution of model, and to manage the rendering of view, whereas the original MVC architecture pattern is presented in the context of winfrom, that is, the traditional C/ s structure of the system, WINFROM structure of the system has one advantage is that its implementation is very convenient, from the view of the presentation to collect data to the controller's dispatch execution model is easy to complete, but ASP.NETMVC is built on the ASP. The MVC schema framework under the web background, so this time the activation of the controller becomes quite troublesome, because the controller is already a string form in the transfer, if it is in C/ s structure so the controller for each processing of the same view will not be activated every time, since the need to activate each time the cache policy, caching policy is only a key point in the controller, need to understand that the controller does need to do a lot of things;

Figure 1:

According to the order of execution, it can be seen that controller controllers play a very important role, all the execution, return value, view rendering all need to manage the scheduling; Of course, the focus of this chapter is to figure out the first step in this diagram, how the controller is loaded and activated, This will involve a large number of helper object models, such as: Controllerfactory controller factory, and the controller factory will use Controllertypecache to cache controller objects, And Conrollertypecache will use Typecacheserializer to the Controller cache file serialization;

3.ASP.NETMVC Controller's entry (System of Controllers inheritance)

Since controller controllers play an important role, it will not be a simple object structure, it has a complex inheritance system and object model to support it to accomplish these arduous tasks, if the controller wants to be able to run, it needs to figure out what its execution portals are, And we need to know which execution portals we need to figure out its inheritance system, which layer is the highest layer of abstraction at the entrance, so that we can extrapolate the many important functions of the Controller;

First we learned that the controller's top-level abstraction is the IController interface, and then the controllerbase abstract class implements the interface, The implementation of the top-level abstraction Controllerbase the method inherited from the IController interface;

123 publicinterface IController {    voidExecute(RequestContext requestContext);}

The code snippet shows that the controller execution requires a RequestContext object, and this object is really the result of the UrlRoutingModule link, The RequestContext object encapsulates the request data obtained during the requests phase, including the request context (HttpContextBase) associated with the HTTP, and most importantly the routing data Object (Routedata) , and the controller's execution must need to routedata in the relevant controller data object, that is, from the request URL through the pattern matching the {Controller} part of the string;

Controllerbase defines some of the common properties used by the controller, such as the tempdata used to hold temporary data, to return to the model data object in view ViewBag, ViewData, and initialize the The ControllerContext object that is used as the data container and operation context for subsequent controllers;

123 protectedvirtual void Initialize(RequestContext requestContext) {    ControllerContext = newControllerContext(requestContext, this);}

In Controllerbase, the Icontroller.execute (RequestContext RequestContext) method call is transferred to the protected abstract void Executecore () method; This is a typical template method pattern, the following inherited class controller, only need to then protected abstract void Executecore () method can be connected with controllerbase;

1 publicabstract classController : ControllerBase

The controller class inherits from the Controllerbase, while the controller's task only needs to complete the Executecore () method;

123456789101112 protected override void ExecuteCore() {           PossiblyLoadTempData();           try {              string actionName = RouteData.GetRequiredString("action");               if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) {                   HandleUnknownAction(actionName);               }           }           finally {               PossiblySaveTempData();           }       }

The code for Controller.executecore () gets the name of the execution action from the Routedata, and then makes an action call through a Actioninvoke component. When the action is executed, it enters into the controller that we inherit, such as: Homecontroller:controller, the method in our custom controller will be regarded as one of the matching targets of action;

Figure 2:

According to the instruction, Controllerbase first realizes the IController interface, completes the implementation of the Execute (RequestContext requestcontext) method, Then the controller inherits the Controllerbase class, overrides the Template Method Executecore () method, and then our custom HomeController is actually the container of action, When the controller's Executecore () method executes, the method call in HomeController is made through the Actioninvoke class;

4.ASP.NETMVC IController Factory Controllers factory (controller creation)

When the controller's inheritance system is clear, the following return to the link of the Mvchandler call; Mvchandler inherits from the IHttpHandler interface, Indicates that it will be the place where ASP. ProcessRequest (HttpContextBase HttpContext) in the method that Mvchandler processes the request; The IController interface will be created via the Icontrollerfactory interface;

The Icontrollerfactory interface is the Controller factory interface, which is designed to implement the factory class for creating IController objects. Within ASP.NETMVC, there is a default factory class that implements the Icontrollerfactory interface Defaultcontrollerfactory,asp.netmvc internally, this class is used to create the IController object;

1 factory = ControllerBuilder.GetControllerFactory();

To get the Idefaultcontrollerfactory interface through the Controllerbuilder object, the Controllerbuilder class is specifically designed to manage icontrollerfactory objects, At the same time, Controllerbuilder is also an application programming interface, which makes the custom Icontrollerfactory object possible;

Creating IController requires us to pass in RequestContext object and controllername controller name;

1234 // Get the controller typestringcontrollerName = RequestContext.RouteData.GetRequiredString("controller");factory = ControllerBuilder.GetControllerFactory();controller = factory.CreateController(RequestContext, controllerName);

Gets the Conroller name of the current request from Requestcontext.routedata, which is then used as the parameter of the Factory.createcontroller;

Figure 3:

Mvchandler the Controllerbuilder object's static property current gets to the Controllerbuilder object instance, apparently Controllerbuilder is an object of a singleton pattern And then get to the Defaultcontrollerfactory default Icontrollerfactory factory object through the Controllerbuilder object. Then the IController object is created using Defaultcontrollerfactory;

King Qingyue Culture

Source:http://wangqingpei557.blog.51cto.com/

This article is copyright to the author and 51CTO shared, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Net/asp.net MVC Controller controllers (I: In-depth analysis of how the controller works)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.