Brief Introduction To Attribue Routing In Web API2


This article provides a brief description of Attribute Routing in Web API2. First we explain about routing, It is a process of matching the URI with the specified action. In routing we use the routing table for determining the action to be performed depending on that action being called.

What Attribute Routing is

Attribute Routing is the new feature of the Web API2. Attribute Routing uses attributes for defining the routes. Attribute Routing is very useful for creating more than one custom route in a controller.

Install the Attribute Routing package from the Nuget Package Manager.

install Attribute Routing package

If you want to use the Attribute Routing for the self-hosting of the Web API then you need to install the Attribute Routing Web API hosted package using the command "Install-Package AttributeRouting.WebApi.Hosted".

How to enable Attribute Routing

For enabling the attribute route we need to use the "config.MapHttpAttributeRoute()" at the time of configuration.

  1. public static void Register(HttpConfiguration config)  
  2. {  
  3.     // Web API configuration and services  
  4.     // Web API routes  
  5.     config.MapHttpAttributeRoutes();  
  6.     config.Routes.MapHttpRoute(  
  7.         name: "DefaultApi",  
  8.         routeTemplate: "api/{controller}/{id}",  
  9.         defaults: new { id = RouteParameter.Optional }  
  10.     );  
  11. } 

How to add a "[Route]" attribute

The "[Route]" attribute is used for defining the prefix in the apicontroller.

  1. [Route("employee/{employeeId}/values")]  
  2. public IEnumerable<Employee>FindOrderByEmployee(int employeeId)  
  3. {  
  4. } 

In the sample code above we defined the "[Route]" indicating the HttpGet method. Here "employee/{employeeId}/values" is the URI.

Now see how we use the "[Route]" attribute for defining the prefix:

  1. public class ValuesController : ApiController  
  2. {  
  3.    [Route("api/values")]  
  4.    public IEnumerable<Employee> Get()  
  5.    {  
  6.    }  
  7.    [Route("appi/values/int:id")]  
  8.    public Employee GetEmployee(int id)  
  9.    {  
  10.    }  
  11. } 

We can also use the "[RoutePrefix]" attribute as a common prefix for the entire controller. We use this prefix before the controller class that works for entire controller.

  1. [RoutePrefix("api/values")]  
  2. public class ValuesController : ApiController  
  3. {  
  4.     [Route("")]  
  5.     public IEnumerable<Employee> Get()  
  6.     {  
  7.     }  
  8.     [Route("int:id")]  
  9.     public Employee GetEmployee(int id)  
  10.     {  
  11.     }  
  12. }   

In the preceding example we can see that we use the "[RoutePrefix]" attribute before the controller class.