Home > Software design >  How to upgrade from ASP.NET MVC Core 2.1 to ASP.NET MVC Core 6?
How to upgrade from ASP.NET MVC Core 2.1 to ASP.NET MVC Core 6?

Time:12-04

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()));
        }
    }

CodePudding user response:

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. As 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 prohram.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 asked sperate 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. 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 realated 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 place above app.Run(); or we can say after var app = builder.Build();.

  • Related