ASP.NET CORE : MVC Routing

Every HTTP request should go to a controller for processing – MVC middleware will make this decision based on the URL and some routing configuration information that we provide, Now one way to define this routing configuration is to define the route for our Controllers inside of Startup.cs when we add MVC middleware – This approach is often referred to as conventional-based routing.

Conventional Routes :  Routing engine will be responsible for mapping each incoming request to appropriate Controller and Action methods with parameters(if any).

In the configure method of Startup.cs class  – we register our MapRoutes as show in below example:

private void configureRoutes(IRouteBuilder routeBuilder)
{
routeBuilder.MapRoute(“Default”, “{controller = Company}/{action=Index}/{id?}”);
}

MapRoute – first parameter is name of route and second parameter is template for route.

Below is sample code for conventional routing:

public class CompanyController : Microsoft.AspNetCore.Mvc.Controller
{
public IActionResult Index()
{
return Content(“Company Index Content..!!”);
}
}

Attribute Routes:  There is limitations on Conventional Routes – problem is that if we want to define different URL patterns for different controllers,we need to define a custom URL pattern that is common to all the controllers.

Attribute based routing will be used to configure custom or different URL patterns at level of Controller and Action methods – This will make it easy to specify what needs to be in URL to reach each controller or action.

Below sample code will provide you configuring Route paths on Controller and Action methods:

[Route(“About”)]
public class AboutController
{
[Route(“Phone”)]
public string PhoneNumber()
{
return “+1 111 111 1111”;
}

[Route(“/admin/[controller]/[action]”)]
public string Address()
{
return “USA”;
}
}

Output on browser: http://localhost:51696/admin/about/address

MiddlewareRouting_1

Output on browser: http://localhost:51696/about/phone

MiddlewareRouting_2

Route attribute on Controller:

[Route(“Employee/[controller]/[action]”)]
public class AboutController
{
public string PhoneNumber()
{
return “+1 111 111 1111”;
}
public string Address()
{
return “USA”;
}
}

Output: http://localhost:51696/Employee/About/PhoneNumber

MiddlewareRouting_3