Introduction
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.
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.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
How to add a "[Route]" attribute
The "[Route]" attribute is used for defining the prefix in the apicontroller.
[Route("employee/{employeeId}/values")]
public IEnumerable<Employee>FindOrderByEmployee(int employeeId)
{
}
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:
public class ValuesController : ApiController
{
[Route("api/values")]
public IEnumerable<Employee> Get()
{
}
[Route("appi/values/int:id")]
public Employee GetEmployee(int id)
{
}
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.
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
[Route("")]
public IEnumerable<Employee> Get()
{
}
[Route("int:id")]
public Employee GetEmployee(int id)
{
}
In the preceding example we can see that we use the "[RoutePrefix]" attribute before the controller class.