[英]How to upgrade from ASP.NET MVC Core 2.1 to ASP.NET MVC Core 6?
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.我开发了一个 ASP.NET MVC Core 2.1 项目,现在我想将它升级到 ASP.NET MVC Core 6,所以我在这里发布了我现有的启动代码、程序 Class 代码和 NuGet 包代码,版本 2.1,请帮助我将我现有的所有代码从 asp.net core 2.1 修改为 asp.net core 6 提前谢谢。
Here are my csproj NuGet Packages that Need to modify to ASP.net Core 6这是我的csproj NuGet 需要修改为 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这是我的启动代码 asp.net core 2.1 需要修改为 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这里是My Program Cs Code asp.net core 2.1需要修改为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这是我的主页示例 Controller asp.net mvc 2.1 需要修改为 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这里是我的登录 Controller 代码 Asp.net core 2.1 需要修改为 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()));
}
}
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
我开发了一个 ASP.NET MVC Core 2.1 项目,现在我想将它升级到 ASP.NET MVC Core 6,所以我在这里发布了我现有的启动代码、程序 Class 代码和 NuGet 包代码,版本 2.1,请帮助我将我现有的所有代码从 asp.net core 2.1 修改为 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:
此外,您还没有分享所有相关参考资料,所以我只考虑从 2.1 到 6 的基本迁移要点。让我们开始吧:
Startup.cs To Program.cs: Startup.cs 到 Program.cs:
As you already know, Asp.net Core 6 has no startup.cs file as it only has program.cs
file.如您所知,Asp.net Core 6 没有 startup.cs 文件,因为它只有
program.cs
文件。 It should looks like below:它应该如下所示:
So while migrating to Asp.net Core 6 we should implement Startup
and ConfigureServices
as below:因此,在迁移到 Asp.net Core 6 时,我们应该按如下方式实现
Startup
和ConfigureServices
:
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:注意:在
program.cs
文件中,您应该考虑以下更改:
Use options.ExpireTimeSpan = TimeSpan.FromHours(2)
instead of options.Cookie.Expiration = new TimeSpan(10,00,00)
使用
options.ExpireTimeSpan = TimeSpan.FromHours(2)
而不是options.Cookie.Expiration = new TimeSpan(10,00,00)
Use builder.Services.AddAuthentication
Instead of services.AddAuthentication
likewise other service as well.使用
builder.Services.AddAuthentication
而不是services.AddAuthentication
同样其他服务也是如此。
Use builder.Services.AddMvc()
Instead of services.AddMvc().SetCompatibilityVersion
使用
builder.Services.AddMvc()
而不是services.AddMvc().SetCompatibilityVersion
Use app.MapControllerRoute(
Instead of app.UseMvc(routes =>
使用
app.MapControllerRoute(
而不是app.UseMvc(routes =>
In addition, as you haven't shared HasAccessRequirment
details so I haven't explain it.此外,由于您尚未共享
HasAccessRequirment
详细信息,因此我没有对其进行解释。 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: 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.注意:在 2.1 中,我们使用
IHostingEnvironment
来处理文件。 Moreover, in Asp.net Core 6 it has changed to IWebHostEnvironment
so bear in mind.此外,在 Asp.net Core 6 中,它已更改为
IWebHostEnvironment
,因此请记住。 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.另一个像
[DisplayName("Dashboard")] [Authorize(policy: "HasAccess")]
这样的middleware
或actionFilter
保持不变,您可以在program.cs
文件中注册为app.UseMiddleware<AutoTimerMiddleware>()
。 You can refer here . 你可以参考这里。
Test User Profile Controller:测试用户简介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. Cspros 文件:我在这里看到你的
cspros
有很多参考资料,但没有相应地分享。 So I have explained only the mandatory migration related reference.所以我只解释了强制迁移相关的参考。
<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.注意:请注意,您应该从 Nuget package 管理器下载
EntityFrameworkCore.Relational
和EntityFrameworkCore.SqlServer
以进行基本迁移。
Output: Output:
Important:重要的:
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.1 中的
ConfigureServices
相关的内容都必须放在 Asp.net Core 6 program.cs
文件的var app = builder.Build()
之上,并且
Anything inside public void Configure
of 2.1 must be placed above app.Run()
or we can say after var app = builder.Build()
. 2.1 的
public void Configure
中的任何内容都必须放在app.Run()
之上,或者我们可以在var app = builder.Build()
之后说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.