Introduction to the ASP. NET Web API Routing Object

Source: Internet
Author: User
Tags hosting webhost

Objective

In the framework of ASP. NET, ASP, and ASP, we find that there are routing figures, they all have the same principle, but some minor changes in different environments, which are based on the characteristics of each framework, and today we'll look at the structure of the route. , although I have written about the length of the route in the MVC series, here is a description of the Web API routing object.

ASP. NET Web API routing, piping
    • ASP. NET Web API Introductory Example
    • ASP. NET Web API Introduction to Routing Objects
    • ASP. NET Web API Piping Model
    • ASP. NET Web API selfhost pipelines, routes in the hosting environment
    • ASP. NET Web API webhost pipelines, routes in the hosting environment

The structure of routing system conceptual routing objects

Figure 1

The most important part of the routing system is the routing object, so let's first look at the definition of "routing object", whether it's a name in the routing system of ASP. NET, ASP, or ASP. In fact, this name is not in the routing object, but in the registration of the routing information, added to the collection of routing objects need to name, here is just as a part of the route, this everyone knows.

It is common and necessary to assign a URL template to a route when generating a routing object, and the conditions for constraining URL templates can be defined according to their own circumstances. At the same time, the framework assigns a "Routing request handler" to the routing object as the main functional part of the cohesive routing system and framework.

registering the route into the system framework

Figure 2

After the route is defined, we will register it in the system framework.

URL matching for routing objects

Figure 3

After the routing object is registered in the system framework, this time, if there is an external request arriving, this time the routing system will make way by the object collection of each route object to match this request, just 4.

Figure 4

This is where the routing object is going to be able to make the behavior of the URL match, according to what to match? is based on the URL template and conditions defined when the routing object is instantiated, the URL of the request information and its own definition of the URL template to match, if there is no successful match will return NULL, this time the framework will let the next route object to match until there is a successful match, If the match succeeds at this time, the route generates a "routed data object".

The routing data object is also important because the following framework functions are used, and it is the crystallization of the entire routing system, and we look at 5

Figure 5

The routing data object maintains a reference to the routing object that generated it, and then the values that hold the value of the routed object after the URL match represent the name of the URL fragment and the corresponding URL true value, while Datatokens is the value that comes directly when the route object definition is generated. Of course, the routing request handler is also caused by the execution of the generated routing object.

In the framework of ASP, ASP, ASP, these frameworks are followed by the above-mentioned process, except that different types are used in different framework environments, and the processes are not the same, but the whole process is consistent, The following 6 illustrates the difference between the types, and more details are not shown.

Figure 6

Also in the Web API (webhost) environment, the route shows that the essence of this is actually the ASP. NET-based routing system is supported, this will be explained in the later Web API series.

The following is a simple demonstration of the routing object registration in various framework environments,

asp:

RouteTable.Routes.MapPageRoute (                "ASP. Netroute ",                " Productinfo/{action}/{id} ",                " ~/productinfo.aspx ",                true,                new RouteValueDictionary {{" ID ", routeparameter.optional}, {" Action "," Show "}}                );

ASP. NET MVC:

            RouteTable.Routes.MapRoute (                "ASP. Netmvcroute ",                " Productinfo/{action}/{id} ",                new {controller=" Product ", action=" show ", id= Routeparameter.optional}                );

ASP. NET Web API (webhost):

            GlobalConfiguration.Configuration.Routes.MapHttpRoute (               "Webapiroute",               "Api/{controller}/{id}", new {id = Routeparameter.optional}               );

ASP. NET Web API (selfhost):

Httpselfhostconfiguration configuration =                 new Httpselfhostconfiguration ("Http://loacalhost/selfhost");            using (httpselfhostserver selfhostserver = new Httpselfhostserver (configuration))            {                SelfHostServer.Configuration.Routes.MapHttpRoute (                    "Defaultapi", "Api/{controller}/{id}", new {id= Routeparameter.optional});                               Selfhostserver.openasync ();                Console.read ();            }

ASP. NET Web API Routing Series Objects

As can be seen from the chart, the ASP. NET WEB API framework in different host environment of the corresponding object type is different, here first introduce the routing system in the Selfhost environment of the routing object bar.

Selfhost Hosting Environment

Web API Routing Objects (System.Web.Http.Routing)

Httproute

    Summary://Represents a routing class that is self-hosted (that is, hosted outside of ASP.) public class Httproute:ihttproute {public Httproute (string routetemplate, httproutevaluedictionary defaults,        httproutevaluedictionary constraints, Httproutevaluedictionary Datatokens, Httpmessagehandler handler);        Public idictionary<string, object> Constraints {get;}        Public idictionary<string, object> datatokens {get;}        Public idictionary<string, object> Defaults {get;}        Public Httpmessagehandler Handler {get;}        public string Routetemplate {get;}        Public virtual Ihttproutedata Getroutedata (string virtualpathroot, httprequestmessage request); Public virtual Ihttpvirtualpathdata GetVirtualPath (httprequestmessage request, idictionary<string, object>        values); Protected virtual bool Processconstraint (Httprequestmessage request, Object constraint, String parametername,    Httproutevaluedictionary values, httproutedirection routedirection); }

You can see from the definition above that the Httproute object represents the Routing object in the Web API framework, and the parameters in the constructor defined by the Httproute type represent the route template, the default value corresponding to the route template, the routing match condition, The values that accompany the registered route and the last HTTP request handlers, which correspond to several attributes in the Httproute type, are understood by themselves.

Web API A collection of Route objects (System.Web.Http)

Httproutecollection

Httproutecollectionextensions

Let's take a look at the extension type of httproutecollection type Httproutecollectionextensions

    public static class Httproutecollectionextensions    {public        static Ihttproute Maphttproute (this Httproutecollection routes, string name, string routetemplate);        public static Ihttproute Maphttproute (this httproutecollection routes, string name, String routetemplate, Object defaults );        public static Ihttproute Maphttproute (this httproutecollection routes, string name, String routetemplate, Object defaults , object constraints);        public static Ihttproute Maphttproute (this httproutecollection routes, string name, String routetemplate, Object defaults , object constraints, Httpmessagehandler handler);    }

Here you can compare the above route registration code, you can know that we are in the route collection to add/register the route is the httproutecollectionextensions type of extension method to operate, At this point, let's look at the implementation of the Maphttproute () method with the most method parameters:

public static Ihttproute Maphttproute (this httproutecollection routes, string name, String routetemplate, Object defaults , object constraints, Httpmessagehandler handler)        {            if (routes = = null)            {                throw System.Web.Http.Error.ArgumentNull ("routes");            }            Httproutevaluedictionary dictionary = new Httproutevaluedictionary (defaults);            Httproutevaluedictionary Dictionary2 = new httproutevaluedictionary (constraints);            idictionary<string, object> datatokens = null;            Httpmessagehandler handler2 = handler;            Ihttproute route = routes. Createroute (Routetemplate, dictionary, Dictionary2, Datatokens, handler2);            Routes. ADD (name, route);            return route;        }

As you can see here, the creation and addition of the Httproute object is performed in this extension method, and now we can look at the definition of the Httproutecollection type and see how to create the Ihttproute object:

    public class Httproutecollection:icollection<ihttproute>, Ienumerable<ihttproute>, IEnumerable, IDispos        Able {public httproutecollection ();        Public httproutecollection (string virtualpathroot);        public virtual int Count {get;}        Public virtual bool IsReadOnly {get;}        Public virtual string Virtualpathroot {get;}        public virtual void Add (string name, Ihttproute route);        Public Ihttproute Createroute (string routetemplate, Object defaults, object constraints); Public Ihttproute Createroute (string routetemplate, idictionary<string, object> defaults, idictionary<string        , object> constraints, idictionary<string, object> datatokens); Public virtual Ihttproute Createroute (string routetemplate, idictionary<string, object> defaults, IDictionary        <string, object> constraints, idictionary<string, object> Datatokens, Httpmessagehandler handler); Public virtual Ihttproutedata GETROutedata (Httprequestmessage request); }

Here is just a part of it, let's take a look at the specific implementation, in fact, is to instantiate a Httproute routing object based on user-configured parameter information:

Public virtual Ihttproute Createroute (string routetemplate, idictionary<string, object> defaults, IDictionary <string, object> constraints, idictionary<string, object> Datatokens, Httpmessagehandler handler)        {            httproutevaluedictionary dictionary = new Httproutevaluedictionary (defaults);            Httproutevaluedictionary Dictionary2 = new httproutevaluedictionary (constraints);            return new Httproute (Routetemplate, Dictionary, Dictionary2, New Httproutevaluedictionary (Datatokens), handler);        }

This is the first function of the Routing object collection type to add/register routing information, what about the second one? is based on the request information to match the routing object, said above, in fact, according to the request to match is not the type of Routing object collection (Httproutecollection), but in each of the routes, we look at the httproutecollection:

Public virtual Ihttproutedata Getroutedata (httprequestmessage request)        {            if (request = = null)            {                throw System.Web.Http.Error.ArgumentNull ("request");            }            foreach (Ihttproute route in this._collection)            {                Ihttproutedata routedata = route. Getroutedata (this._virtualpathroot, request);                if (routedata! = null)                {                    return routedata;                }            }            return null;        }

It can be seen from here that an object that implements the Ihttproutedataroutedata interface is returned when the route match is complete, which is the route data object described above.

Web API Routing Data Objects (System.Web.Http.Routing)

Httproutedata

    public class Httproutedata:ihttproutedata    {public        httproutedata (ihttproute route);        Public Httproutedata (Ihttproute route, httproutevaluedictionary values);        Public Ihttproute Route {get;}        Public idictionary<string, object> Values {get;}    }

In fact, there is no need to talk about it, the above mentioned, the Httproutedata object contains a reference to generate its route object (Httproute), and the values are after the matching route template value, key key corresponding to the URL template fragment value, Value corresponds to the true value of the fragment.

Selfhost in the context of the route here, we look at the following, a simple representation of the route in the selfhost environment of a process, the details will be explained in the following space.

Figure 7

webhost Hosting Environment

Web API Routing Objects (System.Web.Http.WebHost.Routing)

Hostedhttproute

    Internal class Hostedhttproute:ihttproute    {        //Methods public        Hostedhttproute (string uritemplate, Idictionary<string, object> defaults, idictionary<string, object> constraints, idictionary<string, Object> Datatokens, Httpmessagehandler handler);        Public Ihttproutedata Getroutedata (string rootvirtualpath, httprequestmessage request);        Public Ihttpvirtualpathdata GetVirtualPath (httprequestmessage request, idictionary<string, object> values);        Properties public        idictionary<string, object> Constraints {get;}        Public idictionary<string, object> datatokens {get;}        Public idictionary<string, object> Defaults {get;}        Public Httpmessagehandler Handler {get; private set;}        Internal Route Originalroute {get; private set;}        public string Routetemplate {get;}}

As you can see from the code definition above, Hostedhttproute is an assembly internal type and is directly inherited from the Ihttproute interface, which is not related to the Httproute object in the Selfhost environment.

From the internal structure it defines, it is similar to the structure of the Httproute object, or the properties of those objects, the only difference is that there is a Originalroute read-only attribute (externally), which is the encapsulated Httpwebroute object, Look at the implementation of the package

Public Hostedhttproute (String uritemplate, idictionary<string, object> defaults, idictionary<string, Object > Constraints, Idictionary<string, object> Datatokens, Httpmessagehandler handler)    {        RouteValueDictionary dictionary = (defaults! = NULL)? New RouteValueDictionary (defaults): null;        RouteValueDictionary Dictionary2 = (constraints! = NULL)? New RouteValueDictionary (constraints): null;        RouteValueDictionary Dictionary3 = (Datatokens! = null)? New RouteValueDictionary (datatokens): null;        This. Originalroute = new Httpwebroute (UriTemplate, dictionary, Dictionary2, Dictionary3, Httpcontrollerroutehandler.instance, this);        This. Handler = Handler;    }

In the Hostedhttproute object constructor, you can see clearly that the Originalroute property is an instance of an assignment Httpwebroute object, so let's take a look at the definition of the httpwebroute object. :

    Internal class Httpwebroute:route    {        //Fields        Internal const string httproutekey = "Httproute";        Methods Public        httpwebroute (string URL, routevaluedictionary defaults, routevaluedictionary constraints, RouteValueDictionary Datatokens, Iroutehandler Routehandler, Ihttproute httproute);        private static Httproutedirection convertroutedirection (Routedirection routedirection);        private static RouteValueDictionary Getroutedictionarywithouthttproutekey (idictionary<string, object> routevalues);        public override Virtualpathdata GetVirtualPath (RequestContext requestcontext, routevaluedictionary values);        protected override bool Processconstraint (HttpContextBase HttpContext, Object constraint, String parametername, RouteValueDictionary values, routedirection routedirection);        Properties public        Ihttproute Httproute {get; private set;}}

From here you can see that the Httpwebroute object inherits from the route object in ASP., and now it is understood that the Hostedhttproute object holds a reference to the route object in ASP. In the constructor implementation of Hostedhttproute, the origin The Alroute property is an assignment instantiation, at the end of which a httpcontrollerroutehandler type of routing handler is passed in, In fact, it is an assignment to the route handler (Routehandler property) of the route object in ASP. There will be a comprehensive process in the following pages of the specific operations that are routed here.

Web API A collection of Route objects (System.Web.Http.WebHost.Routing

Hostedhttproutecollection

Internal class Hostedhttproutecollection:httproutecollection {//fields private readonly R            Outecollection _routecollection;            Methods public hostedhttproutecollection (RouteCollection routecollection);            public override void Add (string name, Ihttproute route);            public override void Clear ();            public override bool Contains (Ihttproute item);            public override bool ContainsKey (string name);            public override void CopyTo (ihttproute[] array, int arrayindex);            public override void CopyTo (keyvaluepair<string, ihttproute>[] array, int arrayindex); public override Ihttproute Createroute (string uritemplate, idictionary<string, object> defaults, idictionary<            String, object> constraints, idictionary<string, object> Datatokens, Httpmessagehandler handler);            public override ienumerator<ihttproute> GetEnumerator (); public override IHTtproutedata Getroutedata (httprequestmessage request); public override Ihttpvirtualpathdata GetVirtualPath (httprequestmessage request, string name, Idictionary<string,            Object> values);            public override void Insert (int index, string name, Ihttproute value);            private static NotSupportedException notsupportedbyhostedroutecollection ();            private static NotSupportedException notsupportedbyroutecollection ();            public override bool Remove (string name);            public override bool TryGetValue (string name, out Ihttproute route);            Properties public override int Count {get;}            public override Ihttproute This[string name] {get;}            public override Ihttproute This[int index] {get;}        public override string Virtualpathroot {get;} }

Seeing the code definition here, the Hostedhttproutecollection object is also an assembly internal type, inheriting from the RouteCollection object in ASP. Createroute (). The method and the Getroutedata () method return the Hostedhttproute object and the Hostedhttproutedata object, in fact, the Routedata object was originally generated in the Getroutedata () method. It is just a Hostedhttproutedata object that is encapsulated when it returns.

Web API Routing Data Objects (System.Web.Http.WebHost.Routing)

Hostedhttproutedata

Here we look at the definition of the Hostedhttproutedata type:

        Internal class Hostedhttproutedata:ihttproutedata        {            //Methods public            hostedhttproutedata (routedata Routedata);            Properties            Internal Routedata originalroutedata {get; private set;}            Public Ihttproute Route {get; private set;}            Public idictionary<string, object> Values {get;}        }

As you can see from the definition of a constructor, Hostedhttproutedata is the encapsulated Routedata object, which is explained later in the routing process details.

Finally, let's look at the routes in the Webhost host environment.

Figure 8

Introduction to the ASP. NET Web API Routing Object

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.