How to upgrade from ASP.NET MVC Core 2.1 to ASP.NET MVC Core 6?

2k views Asked by At

I have developed an ASP.NET MVC Core 2.1 Project, and Now I want to Upgrade it to ASP.NET MVC Core 6, So I have posted here my existing Startup Code, Program Class Code, and the NuGet Packages Code, version 2.1, Please help me to modify all my existing code from asp.net core 2.1 to asp.net core 6 thank you in advance.

Here are my csproj NuGet Packages that Need to modify to ASP.net Core 6

    <Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
        <NoWin32Manifest>true</NoWin32Manifest>
        <PreserveCompilationContext>true</PreserveCompilationContext>
        <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
        <UserSecretsId>*******************</UserSecretsId>
        <ServerGarbageCollection>false</ServerGarbageCollection>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="BCrypt-Core" Version="2.0.0" />
        <PackageReference Include="ClosedXML" Version="0.97.0" />
        <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="7.8.0" />
        <PackageReference Include="Microsoft.AspNetCore" Version="2.1.7" />
        <PackageReference Include="microsoft.aspnetcore.app" Version="2.1.4" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
        <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.14" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.14" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.14">
            <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
            <PrivateAssets>all</PrivateAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.1" />
        <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.1.1" />
        <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.1" />
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.10" />
        <PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
        <PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.7" />
    </ItemGroup>


</Project>

Here is my Startup Code asp.net core 2.1 that need to modify to asp.net core 6

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration.GetConnectionString("DBconnection");
            services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/Logins/UserLogin/";
                options.AccessDeniedPath = "/AccessDenied";
                options.Cookie.Expiration = new TimeSpan(10,00,00);
            });

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromHours(2);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;

            });
            
            services.ConfigureApplicationCookie(option =>
            {
                option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
            });
 
            services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
            services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                   template: "{controller=UserProfiles}/{action=Index}/{id?}");
            });
        }
    }

Here is My Program Cs Code asp.net core 2.1 need to modify to asp.net core 6

    public static class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
        }
    }

Here is an Example of my Home Page Controller asp.net mvc 2.1 need to modify to asp.net 6

    [DisplayName("Dashboard")]
    [Authorize(policy: "HasAccess")]
    public class HomeController : BaseController
    {
        private readonly IMvcControllerDiscovery _mvcControllerDiscovery;

        private readonly IHostingEnvironment _hostingEnvironment;
        public HomeController(HoshmandDBContext context, IHostingEnvironment hostingEnvironment) : base(context)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        public IActionResult Index(DateTime? date = null)
        {
            date = date ?? GetLocalDateTime();
            ViewBag.date = date;
        }
    }

Here is my Login Controller Code Asp.net core 2.1 need to modify to asp.net core 6

    public class LoginsController : BaseController
    {
        public LoginsController(HoshmandDBContext context) : base(context)
        {
        }
        [HttpGet]
        public async Task<IActionResult> UserLogin()
        {
            return await Task.Run(() => View(new Login()));
        }
    }
1

There are 1 answers

8
Md Farid Uddin Kiron On BEST ANSWER

I have developed an ASP.NET MVC Core 2.1 Project, and Now I want to Upgrade it to ASP.NET MVC Core 6, So I have posted here my existing Startup Code, Program Class Code, and the NuGet Packages Code, version 2.1, Please help me to modify all my existing code from asp.net core 2.1 to asp.net core 6

Well, your question requires too elaborative explanation to answer as it has large context to implement. In addition, you haven't shared all relevant references so I am considering only the basic Migration Essentials from 2.1 to 6. Let's begin:

Startup.cs To Program.cs:

As you already know, Asp.net Core 6 has no startup.cs file as it only has program.cs file. It should looks like below:

enter image description here

So while migrating to Asp.net Core 6 we should implement Startup and ConfigureServices as below:

using Dotnet6MVC.Data;
using Dotnet6MVC.IRepository;
using Dotnet6MVC.Repository;
using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.EntityFrameworkCore;


var builder = WebApplication.CreateBuilder(args);


var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<HoshmandDBContext>(x => x.UseSqlServer(connectionString));

//Authentication
builder.Services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
        {
            options.LoginPath = "/Logins/UserLogin/";
            options.AccessDeniedPath = "/AccessDenied";
           options.ExpireTimeSpan = TimeSpan.FromHours(2);
        });

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(2);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;

});

builder.Services.ConfigureApplicationCookie(option =>
{
    option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
});

//builder.Services.AddAuthorization(options =>
//{
//    options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
//});

//builder.Services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
builder.Services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseSession();

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

Note: Here in program.cs files you should consider below changes:

  1. Use options.ExpireTimeSpan = TimeSpan.FromHours(2) instead of options.Cookie.Expiration = new TimeSpan(10,00,00)

  2. Use builder.Services.AddAuthentication Instead of services.AddAuthentication likewise other service as well.

  3. Use builder.Services.AddMvc() Instead of services.AddMvc().SetCompatibilityVersion

  4. Use app.MapControllerRoute( Instead of app.UseMvc(routes =>

In addition, as you haven't shared HasAccessRequirment details so I haven't explain it. You can ask a separate question for that once you encounter any issue on it.

DbContext:

It will be almost same. I am using this pattern of "Database First" thus you can modify as per your requirement and preference of other pattern like "code first". You can check here for more details

using Microsoft.EntityFrameworkCore;
using Dotnet6MVC.Models;
namespace Dotnet6MVC.Data
{
    public class HoshmandDBContext: DbContext
    {
        public HoshmandDBContext(DbContextOptions<HoshmandDBContext> options) : base(options)
        {
        }
        public DbSet<Users> Users { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           
            modelBuilder.Entity<Users>().ToTable("Users");
           

        }
    }
}

Controller:

using Dotnet6MVC.IRepository;
using Dotnet6MVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace Dotnet6MVC.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IMvcControllerDiscovery _mvcControllerDiscovery;
        private readonly IWebHostEnvironment _hostingEnvironment;

        public HomeController(ILogger<HomeController> logger, IMvcControllerDiscovery mvcControllerDiscovery, IWebHostEnvironment webHostEnvironment)
        {
            _logger = logger;
            _mvcControllerDiscovery = mvcControllerDiscovery;  
            _hostingEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
         
         
            var getLocalDate = _mvcControllerDiscovery.GetLocalDate();
            ViewBag.date = getLocalDate;
            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 });
        }
    }
}

Note: In 2.1 we used IHostingEnvironment for working with files. Moreover, in Asp.net Core 6 it has changed to IWebHostEnvironment so bear in mind. Another point middleware or actionFilter like [DisplayName("Dashboard")] [Authorize(policy: "HasAccess")] remain same as you can register as app.UseMiddleware<AutoTimerMiddleware>() in program.cs file. You can refer here.

Test User Profile Controller:

public class UserProfilesController : Controller
    {
        private readonly HoshmandDBContext _context;
        private readonly IWebHostEnvironment _environment;


        public UserProfilesController(IWebHostEnvironment environment, HoshmandDBContext context)
        {
            _environment = environment;
            _context = context;
        }
        public async Task<IActionResult> Index()
        {
            return View(await _context.Users.Where(u=>u.UserId==10).ToListAsync());
        }
    }

Cspros File: Here I have seen your cspros has lot of reference which not shared accordingly. So I have explained only the mandatory migration related reference.

enter image description here

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <RazorCompileOnPublish>false</RazorCompileOnPublish>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.2" />
  </ItemGroup>

</Project>

Note: Please note that, you should download EntityFrameworkCore.Relational and EntityFrameworkCore.SqlServer from Nuget package manager in order to basic migration.

Output:

enter image description here

Important :

  1. One simple but crucial tips, anything related to ConfigureServices in 2.1 must be placed above var app = builder.Build() of Asp.net Core 6 program.cs file and

  2. Anything inside public void Configure of 2.1 must be placed above app.Run() or we can say after var app = builder.Build().