How to Set up MVC in ASP.NET Core

How to Set up MVC in ASP.NET Core Application

In this article, I will discuss step-by-step instructions on how to set up MVC in the ASP.NET Core Application. Please read our previous article, which briefly introduces the ASP.NET Core MVC Framework.

It is possible in ASP.NET Core (.NET) to build an entire application using only the ASP.NET Core Middleware. However, the ASP.NET Core MVC framework provides the features we can use to easily create HTML Pages and HTTP-Based APIs. So, here I will show you how to set up MVC in ASP.NET Core Application. To do so, let us first create an ASP.NET Core Empty Application. Later on, in this ASP.NET Core MVC article series, we will see examples using the ASP.NET Core Web Application (Model-View-Controller) Project template.

Creating a new ASP.NET Core Empty Application:

To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click on the Create a new project tab, as shown in the image below.

Creating a new ASP.NET Core Empty Application

Once you click on the Create a new project tab, it will open the Create a new project window. You need to select the ASP.NET Core Empty project template from this window and click the Next button, as shown in the image below.

Creating a new ASP.NET Core Empty Application

Once you click on the Next button, it will open the Configure Your New Project window. Here, you need to 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.

How to Set up MVC in ASP.NET Core Application

Once you click on the Next button, it will open the Additional Information window. Here, you need to select .NET 6.0 as the Framework. You also need to check the Configure for HTTPS and do not use top-level statements check boxes. Finally, click on the Create button, as shown in the image below.

How to Set up MVC in ASP.NET Core Application

That’s it. Once you click on the Create Button, the project will be created with the Empty template with the following folder and file structure.

How to Set up MVC in ASP.NET Core Application

The Empty template, by default, does not include the setup for MVC. Let us see how to set up MVC in the ASP.NET Core application.

Setup MVC in ASP.NET Core Application:

ASP.NET Core is a powerful framework for building web applications and APIs, and MVC is a popular design pattern for organizing code in web applications. Setting up an MVC (Model-View-Controller) structure in an ASP.NET Core empty application involves two steps, i.e., configuring the required MVC services and configuring the required Middleware components.

Adding MVC Service to the Request Processing Pipeline:

First, we must 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, which is present within the Program.cs class file as shown below. The builder.Service.AddMVC() statement will include all the required services that are required to develop the ASP.NET core MVC application. Once you add this, you can use Models, Controllers, Views, and many other features in your ASP.NET Core MVC Application.

Adding MVC Service to the Dependency Injection Container

Note: In ASP.NET Core, the AddMvc() method adds MVC services to the application’s services container. This is essential in configuring an ASP.NET Core application to use the Model-View-Controller (MVC) architectural pattern. Along with the AddMVC() method, we also have the AddControllersWithViews() method. In the next article, we will discuss these two methods in detail, as well as the difference between these two methods 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 present within a specific folder called 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 be as shown below.

Adding Controller in ASP.NET Core Application

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 code below 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.

Adding Controller in ASP.NET Core Application

We are not getting the output from the Index action method of the HomeController. The above output comes from the code below, which you can find within the Main method of the Program class.

Adding Controller in ASP.NET Core Application

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 to the application request processing pipeline. To do so, we need to use the UseRouting and UseEndPoints Middleware components, as shown in the below image.

How to Configure our Index Action Method of HomeController as the Default Route?

UseRouting(): It matches a request to an endpoint.
UseEndpoints(): It executes the matched endpoint.

So, modify the Main Method of the Program class as shown below. The MapDefaultControllerRoute() method adds the MVC Middleware to the Request Processing Pipeline of the ASP.NET Core Application.

namespace FirstCoreMVCWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add MVC services to the container.
            builder.Services.AddMvc();

            var app = builder.Build();

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                //Configuring the MVC middleware to the request processing pipeline
                endpoints.MapDefaultControllerRoute();
            });

            //app.MapGet("/", () => "Hello World!");

            app.Run();
        }
    }
}

Now, run the application, and you should get the output as expected, as shown in the below image.

MVC in ASP.NET Core Application

Understanding MapDefaultControllerRoute() Middleware Component in ASP.NET Core

Let’s have a look at the definition of the MapDefaultControllerRoute() middleware. You will see the following in the MapDefaultControllerRoute() method’s definition.

Understanding MapDefaultControllerRoute() Middleware

The above image shows that the default controller is Home, and our application’s default action method is Index. This is the reason why when we run the application, the Index action method of the Home Controller handles the request. But if you want, then you can also change this default behavior as follows:

app.UseEndpoints(endpoints =>
{
     //Configuring the MVC middleware to the request processing pipeline
     endpoints.MapControllerRoute(
     name: "default",
     pattern: "myapp/{controller=Home}/{action=Index}/{id?}");
});

So, in short, to set up MVC in the ASP.NET Core Web Application, first, we need to add the required MVC Services to the dependency injection container, and secondly, we need to configure the MVC Middleware components in the Request Processing Pipeline.

In the next article, I am going to 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 try to 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.

4 thoughts on “How to Set up MVC in ASP.NET Core”

Leave a Reply

Your email address will not be published. Required fields are marked *