AddControllersWithViews() registers the services required for MVC controllers and Razor view rendering in the ASP.NET Core dependency injection container. It prepares an application to return server-rendered HTML through controller actions. section 19.6
Register MVC services in Program.cs
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(); WebApplication app = builder.Build(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); section 19.2
Use the registration with the surrounding MVC setup:
- MapControllerRoute() exposes controllers through conventional routes such as {controller=Home}/{action=Index}/{id?}. section 19.2
- Controllers group action methods, which can return View() and render conventionally located Razor views. section 19.6
- The resulting MVC application can produce output that looks like a Razor Pages application while using different infrastructure. 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 default Program.cs setup, including service registration, middleware, exception handling, and conventional routing. section 19.2
