ASP. NET Web API webhost in the hosting environment, pipelines, routes

Source: Internet
Author: User
Tags hosting webhost

ASP. NET Web API webhost in the hosting environment, preamble to pipelines, routes

In the previous article, referring to a pattern of pipelines and routes in the Selfhost environment of the ASP. NET Web API framework, this article explains what kind of pipelines and routes are in the ASP. NET Web API framework in the WEBHOST environment.

ASP. NET Web API routing, piping
    • The ASP. NET Web API begins with an example
    • Introduction to the ASP. NET Web API Routing Object
    • ASP. NET Web API pipeline model
    • ASP. NET Web API selfhost in the hosting environment, pipelines, routes
    • ASP. NET Web API webhost in the hosting environment, pipelines, routes

ASP. NET Web API webhost in the hosting environment, pipelines, routes

The following will be the main explanation of the route registration execution process (webhost environment), for the pipeline will not be deliberately described, will be included in the route of the explanation, open to explain the effect is not very good.

Httproute->hostedhttproute->httpwebroute->route

To understand clearly the execution of the route and the pattern of the pipeline, you must be familiar with the routing object, but in the previous "ASP. NET Web API Routing Object", it is only a separate description of the routing object types in each environment, and does not explain the process of transformation.

Now, let's talk about the "transition" process for routing objects.

Example code 1-1

        protected void Application_Start (object  sender, EventArgs e)        {            GlobalConfiguration.Configuration.Routes.MapHttpRoute (              "defaultapi"  "Api/{controller}/{id}"new {controller="product ", id = routeparameter.optional});        }

Example code 1-1 is a route registration in a webhost environment, according to the Maphttproute () Method we go to define the past should be a httproutecollection type extension method type Httproutecollectionextensions, Since it's the httproutecollectionextensions type of implementation, let's go over and see what's going on.

Example code 1-2

 Public StaticIhttproute Maphttproute ( ThisHttproutecollection routes,stringNamestringRoutetemplate,ObjectDefaultsObjectconstraints, Httpmessagehandler handler) {            if(Routes = =NULL)            {                ThrowSystem.Web.Http.Error.ArgumentNull ("Routes"); } httproutevaluedictionary Dictionary=Newhttproutevaluedictionary (defaults); Httproutevaluedictionary Dictionary2=Newhttproutevaluedictionary (constraints); IDictionary<string,Object> Datatokens =NULL; Httpmessagehandler Handler2=handler; Ihttproute Route=routes.            Createroute (Routetemplate, dictionary, Dictionary2, Datatokens, Handler2); Routes.            ADD (name, route); returnRoute; }

We can see that the return type is Ihttproute, and the build is implemented by an instance of the Httproutecollection type called the Createroute () method, and here are some friends to ask, is this not the way the route registration is implemented in Selfhost? The answer is right, but using polymorphism in webhost to return to other types, then look down.

Now that you've seen what's happening here, that means there's a route object that inherits a type of httproutecollection type and then creates it. Such a rationale is much clearer, in the selfhost environment the httproutecollection type is present in an object of type httpconfiguration and is not used alone. And in the webhost, too.

This time we look back at the definition in the Globalconfiguration type in code 1-1.

Example code 1-3

Private StaticLazyNewLazyDelegate{httpconfiguration configuration=NewHttpconfiguration (Newhostedhttproutecollection (routetable.routes)); Configuration. Services.replace (typeof(Iassembliesresolver),Newwebhostassembliesresolver ()); Configuration. Services.replace (typeof(Ihttpcontrollertyperesolver),Newwebhosthttpcontrollertyperesolver ()); Configuration. Services.replace (typeof(Ihostbufferpolicyselector),Newwebhostbufferpolicyselector ()); returnconfiguration;        });  Public Statichttpconfiguration Configuration {Get            {                return_configuration.            Value; }        }

From code 1-3 we can see that _configuration static variables using lazy loading, what meaning is the following httpconfiguration type of configuration property if used to instantiate, run off this is not the point.

The point is that in instantiating static variable _configuration It is clear to see that the hostedhttproutecollection type of the route collection type object is used as the constructor parameter. You can take a look at the internal structure of the hostedhttproutecollection on your own.

Now go back to the one that created the route, as shown in code 1-1 and Code 1-2, in the fact that the hostedhttproutecollection type is creating the routing object, which is the usual way to see the implementation code directly.

Example code 1-4

     Public Override Ihttproute Createroute (string uritemplate, idictionary<stringobject> defaults, idictionary<stringobject> Constraints, idictionary<stringobject> Datatokens, Httpmessagehandler handler)    {        returnnew  hostedhttproute (uritemplate, defaults, constraints, Datatokens, handler);    }

It is clear from code 1-4 that the Hostedhttproute route object is returned, and we can look at the constructor so that we know the "transition" process.

     PublicHostedhttproute (stringUriTemplate, idictionary<string,Object> Defaults, idictionary<string,Object> Constraints, idictionary<string,Object>Datatokens, Httpmessagehandler handler) {RouteValueDictionary Dictionary= (Defaults! =NULL) ?NewRouteValueDictionary (defaults):NULL; RouteValueDictionary Dictionary2= (Constraints! =NULL) ?NewRouteValueDictionary (constraints):NULL; RouteValueDictionary Dictionary3= (Datatokens! =NULL) ?NewRouteValueDictionary (Datatokens):NULL;  This. Originalroute =NewHttpwebroute (UriTemplate, dictionary, Dictionary2, Dictionary3, Httpcontrollerroutehandler.instance, This);  This. Handler =handler; }

In code 1-4, we only need to focus on the assignment of the Originalroute property, which is a property of the Hostedhttproute type and is used to set a reference to the route object. In example code 1-4, an object of type Httpwebroute, the constructor for the Httpwebroute object is not cited here. At this point you can see that an object of type Httpcontrollerroutehandler is the Routehandler (route handler) for the route (Httpwebroute) object.

We all know that ASP. NET Web API framework in the WEBHOST environment is dependent on the ASP, but also through the IHttpModule to carry out the early message interception, the following we look at the code in HttpModule (I think it should be so, if wrong please point.) )

Example code 1-5

     Public classWebapihttpmodule:ihttpmodule { Public voidDispose () {Throw Newnotimplementedexception (); }         Public voidInit (HttpApplication context) {context. Postresolverequestcache+=Context_postresolverequestcache; }        voidContext_postresolverequestcache (Objectsender, EventArgs e) {HttpApplication context= Sender asHttpApplication; Httpcontextwrapper Contextwrapper=NewHttpcontextwrapper (context.            Context); Routedata Routedata=RouteTable.Routes.GetRouteData (Contextwrapper); RequestContext RequestContext=NewRequestContext (Contextwrapper,routedata); IHttpHandler HttpHandler=RouteData.RouteHandler.GetHttpHandler (RequestContext); IHttpAsyncHandler Httpasynchandler= HttpHandler asIHttpAsyncHandler; Httpasynchandler.beginprocessrequest (context. Context,NULL,NULL); }     }

In code 1-5 we can see the first is to get the Routedata object instance, to get the Routehandler, and then according to RequestContext get IHttpHandler, and then convert to IHttpAsyncHandler type instance, It then calls its BeginProcessRequest () method to perform the operation.

The above paragraph describes the execution of the above code, some friends may be questioned, how to get routedata?

Here I explain to you, in our code 1-2, there is this code:

            Ihttproute route = routes. Createroute (Routetemplate, dictionary, Dictionary2, Datatokens, handler2);            Routes. ADD (name, route);

First we look at the first sentence, here the route above said is Hostedhttproute object, there is no doubt directly past, and then we look at the second sentence, where the routes is Hostedhttproutecollection object is not false, but this add () The direction added by the method is not hostedhttproutecollection, but what is the current environment, the routetable.routes we said in the Globalconfiguration type at the outset? Asp. NET Framework Environment Yes! There is no doubt that this add () method adds the above-mentioned route (Hostedhttproute object) to the routetable.routes of the current environment, and some friends ask the wrong type. It's wrong. When adding the route (Hostedhttproute object) will be converted to Httpwebroute objects, Httpwebroute objects inherit from the route, you can see the previous space, presumably speaking here you should understand. I'm not going to say much here.

We go back to code 1-5 and get the IHttpHandler instance by Routehandler's Gethttphandler () method after acquiring Routedata. The Routehandler in Routedata is undoubtedly the Httpcontrollerroutehandler type.

Let's take a look at the Gethttphandler () method in the Httpcontrollerroutehandler type:

    protected Virtual IHttpHandler Gethttphandler (requestcontext requestcontext)    {        returnnew  Httpcontrollerhandler (requestcontext.routedata);    }

You can see that the last action is performed by the Httpcontrollerhandler object type, so let's take a look at this type of definition:

 Public class Httpcontrollerhandler:ihttpasynchandler, IHttpHandler

Now you understand why you have to turn into IHttpAsyncHandler, because if you call a function that implements the IHttpHandler interface, it will report an exception, Because the IHttpHandler interface is not implemented in the Httpcontrollerhandler type is just an empty shell, then let's look at the static constructor of the Httpcontrollerhandler type:

Figure 1

This _server is a lazy

Let's take a look at the whole one,

Figure 2

Finally, the Httpcontrollerdispatcher type is explained in the controller section.

Jinyuan

Source: http://blog.csdn.net/jinyuan0829

This article is copyrighted by the author and Csdn, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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.