According to MSDN, Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing.
Introduction
This article demonstrates how to enable attribute routing and describes the various options for attribute routing.
Prerequisites
Visual Studio 2013 or Visual Studio Express 2013
Use NuGet Package Manager to install the necessary packages. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. Enter the following command in the Package Manager Console window:
Install-Package Microsoft.AspNet.WebApi.WebHost
How to set route constraints?
It allows us to restrict the parameters in the route template are matched
The syntax is {parameter:constraint}
In the below example, /Order/8 will Route to the “GetSpecificOrderById” Action.
Here the route will only be selected, if the "orderId" portion of the URI is an integer.
public class OrdersController : Controller
{
// eg: /Order/8
[Route("Order/{orderId:int}")]
public ActionResult GetSpecificOrderById(int orderId)
{
return View();
}
}
How to apply multiple constraints to a parameter ?
We can apply multiple constraints to a parameter, separated by a colon.like this
[Route("Order/{orderId:int:min(1)}")]
public class OrderController : Controller
{
// eg: /Order/8
[Route("Order/{orderId:int:min(1)}")]
public ActionResult GetSpecificPetById(int orderId)
{
return View();
}
}
How to Specify that a parameter is Optional ?
We can do it by Specifying a parameter is Optional (via the '?' modifier).
This should be done after inline constraints. like this
[Route("Order/{message:maxlength(4)?}")]
In the below example, /Order/good and /Order will Route to the “OrderMessage” Action.The route /Order also works hence of the Optional modifier.But /Order/good-bye will not route above Action , because of the maxlength(4) constraint.
[Route("Order/{message:maxlength(4)?}")]
public ActionResult OrderMessage(string message)
{
return View();
}
Conclusion
In this article we have seen how to enable Attribute Routing..In coming articles we will see more on Attribute RoutingReference
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2