Saturday, June 5, 2021

MVC Attribute Routing Concepts

Attribute Routing
In traditional routing in MVC, a route is defined inside the RouteConfig class file whereas in attribute routing, routing pattern is defined inside the controller class just before the action method. There is no need to specify the controller name as it is obvious; implicitly the controller name is the name is which the action method is defined. Also, it is obvious which method will be called because the routing is written just before the action method. The action method is called which is just next below the attribute route definition.

In Attribute routing, following syntax is used to define URL pattern.
Syntax: 
  • [Route("url-pattern-string")]
  • [Route("url-pattern-string", "routeName")]
  • Inside square brackets, routing pattern is defined inside Route. 
Examples 
  • [Route("students")]
  • [Route("students/{id}")]
  • [Route("students/{id}/contact")]
Whatever is written inside the {} is variable or data placeholder inside the url-pattern-string.

Short form Attribute Routes
The above attribute routings can be shortened as students is the common term among all these routings.
[RoutePrefix("students")] will be positioned before the class name and the common term will be removed along with slash, if it exists.
  • [Route("")]
  • [Route("{id}")]
  • [Route("{id}/contact")]
or 
  • [Route("","routeName")]
  • [Route("{id}","routeName")]
  • [Route("{id}/contact","routeName")]

Ambiguous Routes Cases:
Same attribute routes cannot be defined for two action methods. For example, if two action methods have id parameter but their datatypes are different. In this case, we must provide some constructs to distinguish such same attribute routes.
  • [Route("{id:int}")]
  • [Route("{id}")]

Note that datatype is implied after the colon sign. If datatype is not given, it is considered string. Additional constraints can be given after each colon symbol. For example, [Route("{id:int:min(2)}")]

To override the RoutePrefix attribute routing, we can use ~/ sign.

No comments:

Post a Comment

Hot Topics