Create first MVC application using .NET 6 in Visual Studio 2022

In this article, we will create first MVC application using .NET 6 and Visual Studio 2022.

Also, we will see how .NET 6 based MVC project is different from than .NET Core based MVC project.

Prerequisites

Create MVC application in .NET 6

Follow the below steps to create your first MVC application in Visual Studio 2022.

  1. Open Visual Studio 2022 and Click on Create a new project.

2. Search for MVC and select ASP.NET Core Web App(Model-View-Controller) as shown in the below image.

3. Give a name to the project and select Location.

4. Select Framework as .NET 6, leave other selections as default and click on Create.

Below is the directory structure of the .NET 6 MVC application.

Let’s look at code snippets one by one.

Below is the code snippet of HomeController.cs file.

There is no change here if we talk about code structure, constructor, action methods. It looks similar to .NET Core 3.1 Controller class.

using FirstMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace FirstMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Program.cs File – This is one of the major changes in .NET 6. In earlier versions of .NET Core like 3.1 Program.cs file contains 2 major methods –

One is Main() and next one is CreateHostBuilder()

Now in .NET 6, you may notice that CreateBuilder() method is the very first line in Program.cs file.

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

If you have worked in earlier versions of ASP.NET Core then you have noticed the Startup.cs file but here is the twist, there is no more startup.cs file in .NET 6. It can be thought of as a major change in .NET 6 framework.

.NET 6 startup.cs file code is merged in Program.cs file.

For reference, look at startup.cs file below which is the part of MVC .NET Core 3.1

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MVC3_1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

So, by looking at .NET 6 Program.cs file and .NET Core 3.1 startup.cs file we can easily identify that services.AddControllersWithViews(); was part of ConfigureServices() method in .NET Core 3.1 but it is part of Program.cs file in .NET 6.

Similarly, code snippets include built-in middleware in the startup.cs file is now part of the Program.cs file in Dot NET 6.

Let’s run our first MVC application created in .NET 6. Press F5 to see the output.

Summary –

So, in this way we have created our first MVC application in .NET 6 using Visual Studio 2022. In general, we have noticed one major change that is the startup.cs file code snippets are now part of the Program.cs file.

Hope you like this article.

Please share this blog within your tech group and in case you have any feedback, feel free to write it down in the comment box below.

Please follow and like us:

Leave a Comment