Routing is a form of middleware to match URLs of incoming requests and map them to actions.
In Conventional based routing, the route is determined based on the rules defined in the route templates, which will map the incoming Requests(i.e, URLs) to controllers and their action methods. In the ASP.NET Core MVC application, the Convention-based routes are defined within the Configure()
method of the Startup.cs
or Program.cs
class file.
Example
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
This route is considered conventional because it establishes a convention for URL paths. The pattern is:
{controller=Home}
){action=Index}
){id?}
)The mapping is based on the controller and action names only, not on namespaces, file locations, or method parameters.
In Attribute based routing, the route is determined based on the attributes configured at the controller level or the action method level. Though we can use both Conventional and Attribute-Based routing in a single application, attribute routing is primarily used for REST APIs. Attribute routing uses a set of attributes to map actions directly to route templates.
Example
public class HomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
[Route("Home/Index/{id?}")]
public IActionResult Index(int? id)
{
return ControllerContext.MyDisplayRouteInfo(id);
}
[Route("Home/About")]
[Route("Home/About/{id?}")]
public IActionResult About(int? id)
{
return ControllerContext.MyDisplayRouteInfo(id);
}
}
With this style of routing, the controller and action names play no part in which action is matched, unless token replacement is used.
Tokens are a convenience tool for Attribute Routing. There are three tokens (which are identified in square brackets) and when used, tell the route to use the name or the action, area, or controller in place of plain text.
[action]
uses the action name[area]
uses the area name[controller]
uses the controller nameExample of Token Replacement
public class HomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("[controller]/[action]")]
public IActionResult Index()
{
return ControllerContext.MyDisplayRouteInfo();
}
[Route("[controller]/[action]")]
public IActionResult About()
{
return ControllerContext.MyDisplayRouteInfo();
}
}