Along with classic way of route definition MVC WEB API 2 and then MVC 5 frameworks introduced Attribute routing
:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// This enables attribute routing and must go before other routes are added to the routing table.
// This makes attribute routes have higher priority
routes.MapMvcAttributeRoutes();
}
}
For routes with same prefix inside a controller, you can set a common prefix for entire action methods inside the controller using RoutePrefix
attribute.
[RoutePrefix("Custom")]
public class CustomController : Controller
{
[Route("Index")]
public ActionResult Index()
{
...
}
}
RoutePrefix
is optional and defines the part of the URL which is prefixed to all the actions of the controller.
If you have multiple routes, you may set a default route by capturing action as parameter then apply it for entire controller unless specific Route
attribute defined on certain action method(s) which overriding the default route.
[RoutePrefix("Custom")]
[Route("{action=index}")]
public class CustomController : Controller
{
public ActionResult Index()
{
...
}
public ActionResult Detail()
{
...
}
}