[Boiled ASP. NET Web API2 methodology] (3-2) direct routing/attribute routing

Source: Internet
Author: User

Problem

How can you define a route in a way that is closer to the resource (controller,action).

Solution Solutions

You can use attribute routing to declare routes directly at the resource level. Simply use the attribute route Routeattribute on the Action, and then pass a related route template to it. Attribute routing is essentially the same as a centralized route in the meaning of a route template, and all route parameters should use curly braces and match the Action used. Direct routing supports default routing, optional parameters, constraints. For detailed analysis, please go down.

1 [Route ("api/teams/{id}")]2 public Team Getteam ( int ID) 3 {4     // Ignore logic 5 }

If you enable attribute routing, you need to use Httpconfiguration to call the Mapattributeroutes extension method at the application startup location.

Config.maphttpattributeroutes ();

Working principle

An open source class library called Attribute Routing has become a central part of the ASP. NET WEB API 2 architecture. As a result, the pain in the maintenance of centralized routing is addressed, allowing us to declare routes directly on the Controller and Action.

For most developers, attribute routing (the direct route described above) is a more natural approach compared to centralized routing, where attribute routing emphasizes the direct relationship between WEB API resources and URIs, and URI resources should be directly accessible via HTTP. In fact, there are still some popular. NET Web frameworks, for example, ServiceStack, Nancyfx have their own way of defining this resource-close route (embedded Resource).

When the application starts, calling Maphtpatrributeroutes is actually telling the ASP. NET WEB API to scan the attribute routes declared on all controllers.

The reason for this is that the declaration of attribute routing and centralized routing are not much different. Furthermore, their routes are added to the same set of routes as in the previous centralized routing code fragment 3-1. The biggest difference is that direct routing (attribute routing) is added to the route collection as a single composite route (the internal subroutecollection type), and the route key used is MS_ATTRIBUTEROUTEWEBAPI.

When handling each attribute route, the Controller (httpcontrollerdescriptor) or Action (Httpactiondescriptor) Flags the attribute routes that can be accessed. This process is done by adding ms_isattributerouted to the Properties Dictionary of these descriptor types.

Property routing provides some route-custom processing. In fact, you do not have to force the use of Routeattribue to declare routes on controllers and Action. By implementing Idirectroutefactory, you can customize attribute routing, even no attribute routing, and centralized logical routing. The use and Idirectrouteprovider of idirectroutefactory will be discussed again at the end of the 3-11 and 6-8 articles.

Code Demo

In contrast to centralized routing, attribute routing is natural, showing the relationship between the Controller and the Action directly, and also makes it easy to declare complex routes. As shown in the code snippet 3-4 example.

Code Snippet 3-4. Declaring a simple property route

1  Public classTeamscontroller:apicontroller2 {3[Route ("Api/teams/{id}")]4      PublicTeam Getteam (intID)5     {6         //Ignore logic7     }8  9[Route ("Api/teams")]Ten      PublicIenumerable<team>Getteams () One     { A         //Ignore logic -     } -   the[Route ("api/teams/{teamid}/players")] -      PublicIenumerable<player> Getplayers (intteamid) -     { -         //Ignore logic +     } -}

Attribute routing also allows you to define route prefixes through Routeprefixattribute. However, you can only declare at the controller level, modify code snippet 3-4, and define a common prefix for all the routes in the controller. Use the Routeprefixattribute rewrite, as shown in code snippet 3-5. It should be noted that when the route is displayed, all routeattribute specified on the Action are part of the routing template and are spliced behind the routeprefixattribute.

Code Snippet 3-5. Attribute Routing and Routing prefixes

1[Routeprefix ("Api/teams")]2  Public classTeamscontroller:apicontroller3 {4[Route ("{ID}")]5      PublicTeam Getteam (intID)6     {7         //Ignore logic8     }9  Ten [Route] One      PublicIenumerable<team>Getteams () A     { -         //Ignore logic -     } the   -[Route ("{teamid}/players")] -      PublicIenumerable<player> Getplayers (intteamid) -     { +         //Ignore logic -     } +}

As with centralized routing, attribute routing is also dependent on HTTP verb distribution. Therefore, code snippets 3-4 and 3-5 can only handle HTTP GET requests because of a naming convention for routing definitions (the previous article describes the distribution of HTTP verbs).

In order to support other HTTP predicate types, and then add several actions to the Controller, the prefix uses the verb or tag associated with the HTTP verb when naming it. Code Snippet 3-6 has a POST and PUT two types of Action. They all extend the functionality of Teamscontroller to create team resources, create a Player resource into a given team, both POST, and an update Team action (PUT).

Code Snippet 3-6. Supplemental definitions, support for other HTTP verbs

1 [Route]2  PublicHttpresponsemessage Postteam (Team team)3 {4     //Ignore logic5 }6 [HttpPost]7[Route ("{teamid}/players")]8  PublicHttpresponsemessage Addplayer (intTeamid, player player)9 {Ten     //Ignore logic One } A[Route ("{ID}")] -  PublicHttpresponsemessage Putteam (intID, team team) - { the     //Ignore logic -}

[Boiled ASP. NET Web API2 methodology] (3-2) direct routing/attribute routing

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.