What is Attribute Routing? How to do it in ASP.NET MVC 5?

Example Links: https://drive.google.com/file/d/1XFZdb_MtHAsoqe4mQG3_gx5q-K1SnUSJ/view?usp=sharing
In this article we will learn attribute routing and how to implement attribute routing in ASP.NET MVC 5.
ASP.NET MVC 1,2,3,4 support classical URL Routing in ASP.NET MVC 5 we have URL Routing as well as it supports Attribute Routing. Attribute routing is new feature of ASP.NET MVC 5 which enables you to define the url pattern directly on action using [Route] attribute so that you do not need to go to routeconfig.cs and register the routes for the actions. ASP.NET MVC has two attributes for attribute routing -[Route] and [RoutePrefix] attribute where [Route] attribute can be applied on action and [RoutePrefix] Attribute can be applied directly on the controller.
[Route] Attribute: – can be used on action, help you to define the url pattern for the action. directly you can also define multiple url patterns on the same action as follows –
public class TestController : Controller
{
// GET: Test
[Route("my/ind")]
[Route("te/in")]
public ActionResult Index()
{
return View();
}
}
You can also define the url parameters in Route attribute as follows –
[Route("te/cube/{num}")]
[Route("te/{num}/doc")]
public int doCube(int num)
{
return num * num * num;
}
You can also define the constraints to the URL parameters as follows –
[Route("te/cube/{num}")]
[Route("te/{num}/doc")]
public int doCube(int num)
{
return num * num * num;
}
[RouterPrefix] Attribute: – this attribute can be used to define the common prefix that should be get applied to every url pattern defined using [Route] attribute as follows –
[RoutePrefix("Call")]
public class TestController : Controller
{
[Route("my/ind")]
[Route("te/in")]
public ActionResult Index()
{
return View();
}
}