liveBook · Manning

MapControllerRoute

As explained in ASP.NET Core in Action, 3e

MapControllerRoute is an ASP.NET Core endpoint-mapping method that maps MVC controllers using a conventional route template.

MapControllerRoute maps MVC controllers as ASP.NET Core endpoints and gives them a default conventional route. It belongs in Program.cs after MVC services and routing middleware are configured. section 19.2

Default MVC route

A standard MVC application uses: app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); This maps requests to controller actions, defaulting to HomeController, its Index action, and an optional id. section 19.2

Listing 19.1 Program.cs for the default MVC project
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddControllersWithViews();               #1
 
WebApplication app = builder.Build();
 
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");               #2
    app.UseHsts();
}
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
 
app.MapControllerRoute(                                   #3
    name: "default",                                      #3
    pattern: "{controller=Home}/{action=Index}/{id?}");   #4
 
app.Run();
#1 AddControllersWithViews adds the services for MVC controllers with Razor Views.
#2 The exception handler path differs from the default Razor Pages path of /Error.
#3 Adds all MVC controllers in your application using conventional routing
#4 Defines the default conventional route pattern

Inspect the complete Program.cs setup, including AddControllersWithViews, middleware, and the MapControllerRoute call. section 19.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines a conventional route template and defaults, while leaving detailed conventional-routing mechanics for later treatment.
Examples
Uses the default HomeController, Index action, optional id route, and the generated MVC application.
What it assumes
Assumes an ASP.NET Core MVC project and introduces controller endpoint mapping alongside Razor views.
What you can do after
Configure MVC endpoints with a named conventional route in Program.cs.
How it connects
Connects MVC controllers, action methods, Razor views, endpoint routing, and conventional routing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.