Attribute Routing in ASP.NET Web API 2

 

In Web API 1, we had convention-based routing that define routes using route templates. When we create a new Web API project using Visual Studio, a default route is created in WebApiConfig.cs file. The default route is shown below


config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);


With this you mayf ace problem when there are 2 or more get methods or methods with same name, as framework does not know which of the 2 following action methods to map to the URI.

This can be very easily resolved by using Attribute Routing
Using the [Route] attribute to define routes is called Attribute Routing.

Advantages of using Attribute Routing :- Attribute routing gives us more control over the URIs than convention-based routing. Creating URI patterns like hierarchies of resources (For example, students have courses, Departments have employees) i

To achieve this, simply decorate action method with the [Route] attribute, as shwon below,
[Route("api/students/{id}/courses")]



Q. Can we use both Attribute Routing and Convention-based routing in a single Web API project?
Yes, both the routing mechanisms can be combined in a single Web API project. The controller action methods that have the [Route] attribute uses Attribute Routing, and the others without [Route] attribute uses Convention-based routing.

RoutePrefix attribute

RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate the need to repeat that common route prefix on every controller action method

Q. How to override the route prefix?
Use ~ character to override the route prefix, [Route("~/api/ActionName")]



Routing Constraints in ASP.NET Web API

Withroute constraint we can have parameter constrain base routing, the syntax is "{parameter:constraint}"

With these constraints in place, if the parameter segment in the URI is an integer, then Get(int id) method with integer parameter is invoked, if it is a string then Get(string name) method with string parameter is invoked.

NOTE:- "alpha" stands for uppercase or lowercase alphabet characters. Along with int and alpha, we also have constraints like decimal, double, float, long, bool etc. Please check MSDN for the full list of available constraints.

[Route("{id:int}")]
public Employee Get(int id)
{
    //CODE
}

[Route("{name:alpha}")]
public Employee Get(string name)
{
   //CODE
}

Some of the constraints take arguments. To specify arguments use parentheses as shown below.

ConstraintDescriptionExample
minMatches an integer with a minimum value{x:min(0)}
maxMatches an integer with a maximum value{x:max(100)}
lengthMatches a string with the specified length or within a specified range of lengths{x:length(3)} {x:length(1,10)}
minlengthMatches a string with a minimum length{x:minlength(1)}
maxlengthMatches a string with a maximum length{x:maxlength(100)}
rangeMatches an integer within a range of values{x:range(1,100)}


e.g. 

[Route("{id:int:min(1):max(3)}")]
public Student Get(int id)
{
    //CODE
}




Comments