Configuring MVC in ASP.NET Core: A Step-by-Step Guide

Configuring MVC in ASP.NET Core: A Step-by-Step Guide

In this article, we will explore the process of configuring MVC in ASP.NET Core applications. We will cover the two-step process of setting up MVC in ASP.NET Core, including the addition of the HomeController.

Setting Up MVC in ASP.NET Core

So far, we have been using the “empty” project templates in our ASP.NET Core project. However, this project is not currently set up to use MVC. To configure MVC in ASP.NET Core, we need to follow these two steps:

Step 1: Configure the Startup Class

In the Startup.cs file, we need to add the services.AddMvc() line of code in the ConfigureServices() method. This line of code is responsible for adding the MVC service to the container.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

Step 2: Configure the Request Processing Pipeline

In the Configure() method, we need to add the UseMvcWithDefaultRoute() middleware to the request processing pipeline. This middleware is responsible for processing MVC requests and generating responses.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

Note that we have placed the UseStaticFiles() middleware before the UseMvcWithDefaultRoute() middleware in the pipeline. This order is important, as it allows the UseStaticFiles() middleware to process requests for static files (such as images, CSS, or JavaScript files) and avoid unnecessary processing.

Adding the HomeController

To test the MVC configuration, we need to add the HomeController to the project. We can do this by adding a new controller to the “Controllers” folder. The HomeController should have an Index method that returns a string.

public class HomeController
{
    public string Index()
    {
        return "Hello from MVC";
    }
}

Testing the MVC Configuration

After adding the HomeController, we can test the MVC configuration by sending a request to the URL http://localhost:49119. We should see the string “Hello from MVC” displayed in the browser.

Conclusion

In this article, we have covered the two-step process of configuring MVC in ASP.NET Core. We have added the HomeController and tested the MVC configuration by sending a request to the URL http://localhost:49119. We have also discussed the importance of placing the UseStaticFiles() middleware before the UseMvcWithDefaultRoute() middleware in the pipeline.