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()));
}
}
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.csfile. It should looks like below:So while migrating to Asp.net Core 6 we should implement
StartupandConfigureServicesas below:Note: Here in
program.csfiles you should consider below changes:Use
options.ExpireTimeSpan = TimeSpan.FromHours(2)instead ofoptions.Cookie.Expiration = new TimeSpan(10,00,00)Use
builder.Services.AddAuthenticationInstead ofservices.AddAuthenticationlikewise other service as well.Use
builder.Services.AddMvc()Instead ofservices.AddMvc().SetCompatibilityVersionUse
app.MapControllerRoute(Instead ofapp.UseMvc(routes =>In addition, as you haven't shared
HasAccessRequirmentdetails 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
Controller:
Note: In 2.1 we used
IHostingEnvironmentfor working with files. Moreover, in Asp.net Core 6 it has changed toIWebHostEnvironmentso bear in mind. Another pointmiddlewareoractionFilterlike[DisplayName("Dashboard")] [Authorize(policy: "HasAccess")]remain same as you can register asapp.UseMiddleware<AutoTimerMiddleware>()inprogram.csfile. You can refer here.Test User Profile Controller:
Cspros File: Here I have seen your
csproshas lot of reference which not shared accordingly. So I have explained only the mandatory migration related reference.Note: Please note that, you should download
EntityFrameworkCore.RelationalandEntityFrameworkCore.SqlServerfrom Nuget package manager in order to basic migration.Output:
Important :
One simple but crucial tips, anything related to
ConfigureServicesin 2.1 must be placed abovevar app = builder.Build()of Asp.net Core 6program.csfile andAnything inside
public void Configureof 2.1 must be placed aboveapp.Run()or we can say aftervar app = builder.Build().