In this article, we will examine the two key routing methods in ASP.NET Core: MapControllers vs MapControllerRoute, and their differences. They are vital in directing HTTP requests to the appropriate controller actions.

To download the source code for this article, you can visit our GitHub repository.

So, let’s explore the differences and use cases of MapControllers and MapControllerRoute in ASP.NET Core.

Difference Between MapControllers and MapControllerRoute Routing

Routing is an essential feature in ASP.NET Core and is responsible for handling incoming HTTP requests and mapping them to the appropriate endpoints in an application. 

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
To learn more about routing, check out our great article Routing in ASP.NET Core MVC.

In routing setup, we use the MapControllers() method to handle attribute routing in controllers or actions, whereas we use MapControllerRoute() method to establish routing conventions for controllers.

For instance, these methods help manage and direct requests towards specific controllers and their associated actions.

Usage of MapControllers Routing

We use the MapControllers() method to enable attribute-based routing at the controller level of our application. Moreover, this allows us to express controller routes using attributes.

Configure MapControllers

The MapControllers() method enhances control and flexibility, which allows detailed, attribute-focused routing for application route definitions.

Let’s see how we can configure attribute routing in our ASP.NET Core MVC application:

app.MapControllers();

Inside the Program class, we call the app.MapControllers() method to indicate to the application that we want to allow attribute routing.

Creating a Controller for MapControllers

After that, let’s create a new Controller and name it CustomersController. Let’s go ahead and add the attribute base routing to the controller:

[Route("Customers")]
public class CustomersController : Controller
{
    [Route("")]
    [Route("Index")]
    public IActionResult Index()
    {
        return Ok("Customers Index");
    }

    [HttpGet("Info/{id}")]
    public IActionResult Detail(int id)
    {
        return Ok($"Customer {id} Info");
    }
}

Here, we use the RouteAttribute at the controller level which takes one string parameter template to establish a route template for all actions within our CustomersController class. This means that the base path for actions in this controller will start with /Customers.

Additionally, for the Index action, we use two RouteAttribute to specify two route templates "" and Index, which makes the action accessible through two URL paths: /Customers and /Customers/Index. Both routes lead to the same action, which provides flexibility to access the Index action.

Also, the Detail action is a parameterized route which uses the HttpGetAttribute and accepts a string parameter template Info/{id}. As a result, the action is accessible through an HTTP GET request via the URL path /Customers/Info/4 where 4 is the value of the id parameter in the route template string.

Lastly, let’s look at a few more examples of using attributes:

[Route("Order")]
[Route("Customer/Order")]
public IActionResult Order()
{
    return Ok("Customers Order");
}

[HttpGet("/special")]
public IActionResult SpecialRoute()
{
    return Ok("Customers SpecialRoute");
}

Here, we associate the Order action with two RouteAttribute, Order and Customer/Order. Thereby, we allow the action to be accessible through two distinct URL paths: /Order and /Customer/Order.

For the SpecialRoute() action, we configure it with an absolute path route with HttpGetAttribute, we use /special as our parameter. Furthermore, this specifies that the action can be directly accessible through a GET request using the URL path /special regardless of the controller-level route of the CustomersController class. This differs from relative routes, it will bypass the usual controller-level route templates.

Usage of MapControllerRoute Routing

The MapControllerRoute() method allows us to configure a consistent mapping between URL patterns and controller actions. Therefore, it allows us a convention-based approach to define routing templates that follow common URL structures for our web app.

That is, it allows routing configuration without explicitly using attributes on controllers and actions. Instead, it depends on conventions and it presents a practical choice for situations where an attribute-based approach may be less fitting or where a combination of conventions and attributes is preferred.

Next, let’s look at the usage of MapControllerRoute() in our application:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

Here, we configure a default route for controllers in the Program class of our application. Let’s break the route configuration down for better understanding.

We use the name parameter to give the route a name. In this case, we name it default.

For the second parameter, pattern we use a template to define the route with a specific pattern:

PatternExplanation
{controller=Home}This part of the pattern represents the controller. If the URL does not explicitly specify a controller, it defaults to Home
{action=Index}This part stands for the action name. If the URL does not specify an action, it defaults to Index
{id?}This part is for an id parameter which can be null. This is equivalent to the parameterized route in the MapControllers example above. The ? indicates that the id parameter is optional. If present in the URL, its value is captured; otherwise, it's null.

Evidently, MapControllerRoute() allows us to define routes to make it easier to understand and manage. Specifically, MapControllerRoute is sometimes called conventional routing because it follows a convention-based approach to define routes.

Choosing Between MapControllers and MapControllerRoute

How can we determine the appropriate usage of MapControllers() or MapControllerRoute()?

Let’s summarize the key points between the different methods:

MapControllersMapControllerRoute
Routes configuration is done through attributes.Routes configurations are convention-based
Suitable for Web API applicationSuitable for conventional ASP.NET Core MVC application
Ideal when routing requirements are complexIdeal for simple routing requirements
Harder to maintain due to explicit routing configurations for controllers and actionsEasier to maintain due to standardized routing configuration
Ideal for explicit route definitions and customization requirementIdeal for situations where a standardized routing method is preferred

Conclusion

MapControllers is attribute-based routing at the controller level, which allows detailed and flexible route definition using attributes.

MapControllerRoute is a convention-based routing, it provides a standardized mapping between URL patterns and controller actions without the explicit use of attributes.

The choice between MapControllers and MapControllerRoute depends on the nature of the application, complexity, and maintenance priorities.

Consider Web API applications, complex routing requirements, and customization needs when choosing MapControllers. But, for conventional MVC applications with simplicity in mind and a focus on maintenance ease, MapControllerRoute is the recommended choice.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!