How the ASP. NET Web API Controller was built

Source: Internet
Author: User

First look at the ASP. NET WEB API message pipeline:

Note: In order to prevent the image from being too large to exceed the layout, the "http message handler" block omits the portion of the Httproutingdispatcher processing route assignment. The "controller" block omits the processing details of the filter. Microsoft Web site provides a more complete Web API message processing flowchart, the URL is http://www.microsoft.com/en-us/download/details.aspx?id=36476.

This message pipeline architecture diagram is divided into three layers, from top to bottom, namely load (Hosting), message handler (message handlers), and controller. The red solid arrows in the graph represent HTTP request messages, and the dashed arrows represent HTTP response messages. The message processing flow is as follows:

    1. When the client's HTTP request to the server begins to enter the ASP. NET Web API framework, the HTTP request message is packaged as a Httprequestmessage object and enters the httpserver of the top "mount" block in the diagram (Web Load) or httpselfhostserver (self-loading). The message then flows into the next stage of the pipeline until the entire message flow is processed, and a Httpresponsemessage object representing the HTTP response message is obtained, and the message content of the object is passed back to the client.
    2. The Httprequestmessage object enters the message handler pipeline. At this stage, the HTTP message passes through a number of message handlers (message handlers) and executes in reverse order when the HTTP response message is returned.
    3. After each message handler, the HTTP request message is then passed to Httpcontrollerdispatcher, and the object establishes the Web API controller and then passes the HTTP request to the Controller object (the "(A) steps to establish the controller" ").
    4. The Controller will first determine the target action method (which is shown in the figure "(B) Select the action" Step), and then call it. " The action method is responsible for generating the response content, which is then returned along the reverse direction of the pipeline process.

The above is the approximate processing flow of the Web API HTTP message pipeline.

Web API Controller How was it built?

Just to illustrate the general process of the Web API HTTP message pipeline, and to inject the dependent object into the controller category of the constructor, or to move some hands and feet to change the default behavior, you will have to understand the Web API framework to establish the internal process of controller. This section will further explain the complex links, which will be repeated reference to a number of abstract interfaces, the first reading may be slightly difficult, and inevitably heart confusion, but wait until the actual written, run over the back of the sample program, and then look back to this section of the explanation, the whole puzzle should be gradually clear.

As mentioned earlier, Httpcontrollerdispatcher will establish the target controller object, that is, the previous ASP.

The API pipeline architecture diagram identifies "(A) the steps to establish a controller". This step actually contains two pieces of work:

    1. Resolves the target controller. That is, decide which controller class to use.
    2. An instance of the target controller class is established and the HTTP request (Httprequestmessage object) is passed to it for subsequent processing by the controller.

First, the task of resolving the target controlleris to look for all the available controller classes from the application's DLL component , and then select one from the current HTTP request Match. Its processing logic is as follows:

Description

    • The Getassemblies method for the Iassembliesresolver object below the figure will provide a list of components for the application. The list of controller categories available is obtained by the Getcontrollertypes method of the Ihttpcontrollertyperesolver object.
    • Ihttpcontrollerselector is responsible for deciding which controller category to select, It then returns a Httpcontrollerdescriptor object containing its type information to Httpcontrollerdispatcher.

from the determination of the target controller type to the completion of the controller instance, there are some extensibility points provided by some core standard interfaces. At the bottom, we use a UML activity diagram with the Web API source code to deconstruct its internal process.

The description is as follows (corresponding to the numeric number in):

(1) Httpcontrollerdispatcher obtains the target controller type information through the Selectcontroller method of the Ihttpcontrollerselector object, This type of information is wrapped in a Httpcontrollerdescriptor object.

(2) Httpcontrollerdispatcher then calls the Createcontroller method of the Httpcontrollerdescriptor object, And this method will call the Servicescontainer object's Gethttpcontrolleractivator method to get the Ihttpcontrolleractivator object. The following program fragment is excerpted from the Web API source code, which covers some of the logic for this step to the next step:

// the Createcontroller method for the Httpcontrollerdescriptor category.  publicvirtual  ihttpcontroller Createcontroller (httprequestmessage request) {    = Configuration.Services.GetHttpControllerActivator ();      This , Controllertype);      return instance;}

(3) After acquiring the Ihttpcontrolleractivator object, it then calls its Create method, and this method calls its own Getinstanceoractivator method to obtain the controller instance. The following program fragment was taken from the original code of the Defaulthttpcontrolleractivator category, and I removed the error handling and quick-fetch mechanism and added Chinese annotations:

//defaulthttpcontrolleractivator category Create method (re-click) PublicIhttpcontroller Create (httprequestmessage request, Httpcontrollerdescriptor Controllerdescriptor, Type Controlle Rtype) {Func<IHttpController>Activator; Ihttpcontroller Controller=getinstanceoractivator (Request, Controllertype, outactivator); if(Controller! =NULL)    {        //Register to the Web API Framework Dependency Resolver//has established this controller type of the Execute.         returnController//then use this object directly.     }    //Target Controller Object not yet established    returnActivator ();//then use the Getinstanceoractivator method to send back the delegate to build the object}

(4) The Getinstanceoractivator method of the Ihttpcontrolleractivator object calls the Httprequestmessage expansion method Getdependencyscope to obtain the current The Idependencyscope object associated with the request
(It's actually a Service Locator) and uses its GetService method to get the controller object. If the GetService method does not return a controller object, but returns Null (on behalf of a service type that cannot be resolved), then returns to the second, using the type Reflection (reflection) mechanism to establish the Controller object. As with the original code to see:

//excerpted from DefaultHttpControllerActivator.csPrivate StaticIhttpcontroller Getinstanceoractivator (httprequestmessage request, Type Controllertype, outFunc<ihttpcontroller>>activator) {   //If dependency scope has a controller object returned, it is used. Ihttpcontroller instance =(Ihttpcontroller) request. Getdependencyscope ().   GetService (Controllertype); if(Instance! =NULL) {Activator=NULL; returninstance; }   //Otherwise, establish a delegate to create instances of this type. Activator = typeactivator.create<ihttpcontroller>(Controllertype); return NULL;}

One of the request. Getdependencyscope () is the extension method that corresponds to the call httprequestmessage that you just said Getdependencyscope to get the Idependencyscope object associated with the current request. "And the Idependencyscope object actually obtained here will be the default implementation provided by the WEB API framework: Emptyresolver. From the category name, this category actually does nothing--its GetService method returns NULL. Thus, in a preset scenario, the WEB API framework uses the type-reflection (reflection) mechanism to create the Controller object, which is why our controller class must have a preset constructor (default constructor) for the sake of.

In general, this is how the Controller object is built.


This digest is from the 5th chapter of the book ". NET Dependency Injection".

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.