Back to: ASP.NET Core Tutorials For Beginners and Professionals
How to Set up MVC in ASP.NET Core Application
In this article, I will discuss how to set up MVC in ASP.NET Core Web Application step by step with Examples. Please read our previous article, which briefly introduces the ASP.NET Core MVC Framework.
In ASP.NET Core (.NET), it is possible to build an entire application using only the ASP.NET Core Middleware component. However, the ASP.NET Core MVC framework provides the features we can use to create HTML Pages and HTTP-based APIs easily. So, I will show you how to set up MVC in the ASP.NET Core Application.
Creating a new ASP.NET Core Empty Application:
Let us first create an empty ASP.NET Core application. Later, in this ASP.NET Core MVC article series, we will see examples using the ASP.NET Core Web Application (Model-View-Controller) Project template. To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click the Create a new project tab, as shown in the image below.
Once you click on the Create a new project tab, the Create a new project window will open. In this window, select the ASP.NET Core Empty project template and click the Next button, as shown in the image below.
Once you click on the Next button, it will open the Configure Your New Project window. Here, provide the necessary information to create a new project. First, give an appropriate name for your project (FirstCoreMVCWebApplication), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.
Once you click on the Next button, it will open the Additional Information window. Here, you need to select .NET Framework. You also need to check the Configure for HTTPS and do not use top-level statements check boxes. Finally, click the Create button, as shown in the image below.
Once you click the Create button, a new ASP.NET Core Web Application will be created in Visual Studio 2022 using .NET 8. The project will have the following file and folder structure.
By default, the Empty template does not include the MVC setup. Let’s see how to set up MVC in the ASP.NET Core application.
How to Setup MVC in ASP.NET Core Application:
Setting up the MVC (Model-View-Controller) in the ASP.NET Core Application involves two steps: Configuring the Required MVC Services and Middleware Components in the Request Processing Pipeline.
Adding MVC Service to the Request Processing Pipeline:
First, we need to add the required MVC services to the Application Request Processing Pipeline. To do so, we need to modify the Main method of the Program class as follows. The builder.Service.AddMVC() statement will include all the services required to develop the ASP.NET Core MVC application. Once you add this, you can use Models, Controllers, Views, TempData, ViewData, ViewBag, and many other features in your ASP.NET Core MVC Application.
Note: In ASP.NET Core, along with the AddMVC() method, we also have the AddControllersWithViews() method. In the next article, we will discuss these two methods in detail, their differences, and when to use one over another.
Adding Controller in ASP.NET Core MVC Application:
In the ASP.NET Core MVC application, all the Controllers should be in a specific folder named Controllers. So first, create a folder named Controllers within the project root directory. Once you add the Controllers folder, add a new class file named HomeController.cs within the Controllers folder. Once you add the HomeController class, your project folder structure should look as shown below.
Now open the HomeController.cs class file and copy and paste the following code. To make a class as a controller in ASP.NET Core MVC, that class must be inherited from the Controller base class. So, you can see in the below code that our controller, i.e., HomeController, is inherited from the Controller base class. This Controller base class belongs to Microsoft.AspNetCore.Mvc namespace.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCWebApplication.Controllers { public class HomeController : Controller { public string Index() { return "This is Index action from MVC Controller"; } } }
With the above changes in place, now run the application, and you will get the following output.
We are not getting the output from the HomeController’s Index action method. The above output comes from the MapGet method, which you can find within the Program class’s Main method.
How Do We Configure our Index Action Method of HomeController as the Default Route?
We need to tell the ASP.NET Core MVC Framework to use the Index action method of our Home Controller as the default route. To do so, we must add the Required MVC Middleware Component (UseRouting and MapDefaultControllerRoute) to the application request processing pipeline.
UseRouting Middleware in ASP.NET Core:
The UseRouting middleware adds the routing capabilities to the request processing pipeline. Its primary objective is to match incoming HTTP requests to the corresponding route endpoint definitions.
- By adding UseRouting, we enable the application to use route matching.
- It matches the incoming request URL to the routes that are defined in the application. This is essential for directing requests to the appropriate controllers and actions.
- It should be placed before middleware, which depends on route matching, such as MapDefaultControllerRoute.
- Syntax: app.UseRouting();
MapDefaultControllerRoute Middleware in ASP.NET Core:
The MapDefaultControllerRoute method is a shorthand method to configure the default route for MVC controllers. Its primary objective is to set up a conventional routing pattern that maps URLs to controllers and actions using a predefined template.
- It uses the default routing template {controller=Home}/{action=Index}/{id?}. This means that if no specific route is provided, the request will be directed to the HomeController and its Index action.
- This method ensures that requests are routed to the appropriate controller and action method based on the URL.
- Syntax: app.MapDefaultControllerRoute();
So, modify the Main Method of the Program class as shown below. The UseRouting() and MapDefaultControllerRoute() Middleware Components add the MVC Middleware to the Request Processing Pipeline.
namespace FirstCoreMVCWebApplication { public class Program { public static void Main(string[] args) { // Create a WebApplication builder, which provides various configuration settings // and services for the web application var builder = WebApplication.CreateBuilder(args); // Add MVC services to the service container. // This includes support for controllers and views. builder.Services.AddMvc(); // Build the application using the configured builder var app = builder.Build(); // Enable routing middleware, which matches incoming HTTP requests to endpoints defined in the application app.UseRouting(); // Map the default controller route (convention: {controller=Home}/{action=Index}/{id?}) // This means if no specific route is provided, it will default to HomeController and Index action app.MapDefaultControllerRoute(); // Run the application, which blocks the calling thread and starts listening for incoming HTTP requests app.Run(); } } }
Run the application, and you should get the expected output, as shown in the image below.
How do we specify a custom controller and action method?
The MapDefaultControllerRoute() middleware uses Home as the default Controller and Index as the default action method for our application. This is why when we run the application, the Index action method of the Home Controller handles the request. But you can also change this default behavior. To do so, we need to use the MapControllerRoute Middleware component instead of the MapDefaultControllerRoute() middleware and specify the default controller and action.
MapControllerRoute Middleware Component:
The MapControllerRoute method is used to define a custom route for MVC controllers in an ASP.NET Core application. Its primary objective is to map incoming HTTP requests to specific controllers and actions based on a defined URL pattern.
- It allows us to specify custom URL patterns that map to controllers and actions, providing flexibility in how URLs are structured.
- It also defines a custom URL pattern that specifies how URLs should be parsed and matched to controller actions.
- We can also define multiple routes using MapControllerRoute to handle different URL patterns and route them to different controllers and actions.
Note: We will discuss Routing in detail in our upcoming articles.
So, modify the Main method of the Program class to use the MapControllerRoute Middleware component instead of the MapDefaultControllerRoute() middleware as follows.
namespace FirstCoreMVCWebApplication { public class Program { public static void Main(string[] args) { // Create a WebApplication builder, which provides various configuration settings // and services for the web application var builder = WebApplication.CreateBuilder(args); // Add MVC services to the service container. // This includes support for controllers and views. builder.Services.AddMvc(); // Build the application using the configured builder var app = builder.Build(); // Enable routing middleware, which matches incoming HTTP requests to endpoints defined in the application app.UseRouting(); // Map the default controller route (convention: {controller=Home}/{action=Index}/{id?}) // This means if no specific route is provided, it will default to HomeController and Index action app.MapControllerRoute( name: "default", // Name of the route pattern: "{controller=Home}/{action=Index}/{id?}" // URL pattern for the route ); // Run the application, which blocks the calling thread and starts listening for incoming HTTP requests app.Run(); } } }
Now, run the application, and you should get the output as expected.
So, in short, to set up MVC in the ASP.NET Core Web Application, we first need to add the required MVC Services to the dependency injection container and then configure the required MVC Middleware Components to the Request Processing Pipeline.
In the next article, I will discuss the differences between AddController(), AddMvc(), AddControllersWithViews(), and AddRazorPages() Methods and when to use one over another in ASP.NET Core MVC application. In this article, I explain step-by-step how to set up MVC in ASP.NET Core Web Application with an example. I hope you enjoy this MVC Setup in ASP.NET Core Web Application article.
why this tutorial not working for ASP.net core 3.1. Great Jobe!
Initially, this tutorial was created based on .NET Core 2.2. But now we are updating it to .NET 8. In a few days, you will find everything related .NET 8.
Is the this tutorial available in .Net core 3.1
No. This Course Targeted Framework is .NET 8 and later version of .NET
very informative tutorial