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

Source: Internet
Author: User

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

Problem

How can I define a route in a way closer to a resource (Controller or Action.

 

Solution

You can use Attribute routing to directly declare a route at the resource level. You only need to simply use RouteAttribute on the Action, and then pass a relevant routing template. Attribute routing and centralized routing basically have the same meaning in the routing template. All routing parameters should be in curly brackets and must match with the used Action. Direct routes support default routes. Optional parameters and constraints. For detailed analysis, go down.

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

 

To enable attribute routing, you must use HttpConfiguration to call the extension method of MapAttributeRoutes at the application startup location.

Config.MapHttpAttributeRoutes();

 

Working Principle

An open-source class library named Attribute Routing has become the core part of the ASP. net web api 2 architecture. This solution solves the pain caused by the maintenance of centralized routes, allowing us to declare routes directly on the Controller and Action.

 

For most developers, attribute routing (direct routing mentioned above) is a more natural method than centralized routing. Attribute routing emphasizes the direct relationship between web api resources and Uris, the URI resource can be accessed directly through HTTP. In fact, there are still some popular. NET Web frameworks. For example, ServiceStack and NancyFx all have their own methods to define such routes close to resources (embedded resources ).

 

When an application is started, MapHtpAtrributeRoutes is called to tell ASP. net web api to scan all attribute routes declared on the Controller.

 

The reason is that there is no big difference between the attribute routing and the centralized routing. In addition, their routes are added to the same routing set as the previous centralized routing code segment 3-1. The biggest difference is that direct routing (attribute Routing) is added to the routing set as a single composite routing (internal SubRouteCollection type), and the routing key used is MS_attributerouteWebApi.

 

When processing each attribute route, the Controller (HttpControllerDescriptor) or Action (HttpActionDescriptor) will mark the attribute route that can be accessed. This process is completed by adding MS_IsAttributeRouted to the Properties Dictionary of the descriptor type.

 

Attribute routing provides custom routing. In fact, you do not have to force RouteAttribue to declare a route on the Controller and Action. By implementing IDirectRouteFactory, you can customize attribute routing, or even non-attribute routing, and centralize logical routing. The use of IDirectRouteFactory and IDirectRouteProvider will be discussed again later in Articles 3-11 and 6-8.

 

Code demo

In contrast to a centralized route, a property route is natural, directly displaying the relationship between the Controller and Action, and easily declaring a complex route. See sample code snippet 3-4.

 

Code snippet 3-4. Declare a simple property route

1 public class TeamsController: ApiController 2 {3 [Route ("api/teams/{id}")] 4 public Team GetTeam (int id) 5 {6 // ignore Logic 7} 8 9 [Route ("api/teams")] 10 public IEnumerable <Team> GetTeams () 11 {12 // ignore logic 13} 14 15 [Route ("api/teams/{teamId}/players")] 16 public IEnumerable <Player> GetPlayers (int teamId) 17 {18 // ignore logic 19} 20}

 

Attribute routing can also define the route prefix through RoutePrefixAttribute. However, you can only declare it at the Controller level and modify the code snippet 3-4 to define a public prefix for all the routes in the Controller. Use RoutePrefixAttribute for rewriting, as shown in code snippet 3-5. Note that when a route is displayed, all routeattributes specified on the Action are part of the routing template and are spliced after RoutePrefixAttribute.

 

Code snippet 3-5. Attribute routing and route prefix

1 [RoutePrefix ("api/teams")] 2 public class TeamsController: ApiController 3 {4 [Route ("{id}")] 5 public Team GetTeam (int id) 6 {7 // ignore logic 8} 9 10 [Route] 11 public IEnumerable <Team> GetTeams () 12 {13 // ignore logic 14} 15 16 [Route ("{teamId}/players")] 17 public IEnumerable <Player> GetPlayers (int teamId) 18 {19 // ignore logic 20} 21}

 

Similar to a centralized route, property routes also rely on HTTP predicate distribution. Therefore, because of the naming conventions for routes (HTTP predicate distribution described in the previous article), code snippets 3-4 and 3-5 can only process http get requests.

 

In order to support other HTTP prefix types, add several actions in the Controller. when naming, use the HTTP prefix related verb or tag. Code snippets 3-6 have two types of actions: POST and PUT. All of them have extended the TeamsController function. They can create Team resources and create a Player resource to a given Team. Both are POST and a Team update operation (PUT ).

 

Code snippet 3-6. Additional definitions, support for other HTTP predicates

1 [Route] 2 public HttpResponseMessage PostTeam (Team team) 3 {4 // ignore logic 5} 6 [HttpPost] 7 [Route ("{teamId}/players")] 8 public HttpResponseMessage AddPlayer (int teamId, Player player) 9 {10 // ignore logic 11} 12 [Route ("{id}")] 13 public HttpResponseMessage PutTeam (int id, team team) 14 {15 // ignore Logic 16}

 

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.