Original: http://www.strathweb.com/2015/01/asp-net-mvc-6-attribute-routing-controller-action-tokens/
When you use Routing properties in Web API 2 or MVC 5, it is very easy to take a situation where the routing and controller names are not synchronized. This is because the route is usually a string, so when we change the name of the controller we also have to modify the routing properties.
We usually forget to change it at that time.
This problem has been improved in MVC 6 – by introducing [controller] and [action] tokens to the route properties.
Problem
The controller code for a typical Web API project is as follows:
[Route ("Api/hello")]public class hellocontroller:controller{ [route] public string Get () { return "Hello"; }}
Or:
[Route ("Api/hello")]public class hellocontroller:controller{ [Route ("Gethello")] public string Gethello () { return "Hello"; }}
In the two examples above, we usually need to manually maintain the route properties.
MVC6 Solutions
By using the new [controller] token you can ensure that your routing and controller names remain the same. In the example below, [controller] is always the same as the name of the controller – in this case the name of the route is Hello.
[Route ("api/[controller]")]public class hellocontroller:controller{ [route] public string Get () { return "Hello"; }}
[Action] token– This app keeps the name of the route and action consistent on the Aciton.
In the following example, the action matches the /API/HELLO/GETHELLO/1 URL.
[Route ("Api/[controller]")]public class hellocontroller:controller{ [Route ("[Action]/{id:int}")] public string Gethello (int id) { return "Hello" + id; }}
ASP. NET MVC 6 attribute routing–the [controller] and [action] tokens