繁体   English   中英

如何从 ASP.NET MVC Core 2.1 升级到 ASP.NET MVC Core 6?

[英]How to upgrade from ASP.NET MVC Core 2.1 to ASP.NET MVC 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 提前谢谢。

这是我的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>

这是我的启动代码 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?}");
            });
        }
    }

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

这是我的主页示例 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;
        }
    }

这里是我的登录 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()));
        }
    }

我开发了一个 ASP.NET MVC Core 2.1 项目,现在我想将它升级到 ASP.NET MVC Core 6,所以我在这里发布了我现有的启动代码、程序 Class 代码和 NuGet 包代码,版本 2.1,请帮助我将我现有的所有代码从 asp.net core 2.1 修改为 asp.net core 6

好吧,您的问题需要过于详尽的解释才能回答,因为它有很大的实施背景。 此外,您还没有分享所有相关参考资料,所以我只考虑从 2.1 到 6 的基本迁移要点。让我们开始吧:

Startup.cs 到 Program.cs:

如您所知,Asp.net Core 6 没有 startup.cs 文件,因为它只有program.cs文件。 它应该如下所示:

在此处输入图像描述

因此,在迁移到 Asp.net Core 6 时,我们应该按如下方式实现StartupConfigureServices

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

注意:program.cs文件中,您应该考虑以下更改:

  1. 使用options.ExpireTimeSpan = TimeSpan.FromHours(2)而不是options.Cookie.Expiration = new TimeSpan(10,00,00)

  2. 使用builder.Services.AddAuthentication而不是services.AddAuthentication同样其他服务也是如此。

  3. 使用builder.Services.AddMvc()而不是services.AddMvc().SetCompatibilityVersion

  4. 使用app.MapControllerRoute(而不是app.UseMvc(routes =>

此外,由于您尚未共享HasAccessRequirment详细信息,因此我没有对其进行解释。 一旦遇到任何问题,您可以单独提出一个问题。

数据库上下文:

这几乎是一样的。 我正在使用这种“数据库优先”模式,因此您可以根据您的要求和对其他模式(如“代码优先”)的偏好进行修改。 您可以在此处查看更多详细信息

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

注意:在 2.1 中,我们使用IHostingEnvironment来处理文件。 此外,在 Asp.net Core 6 中,它已更改为IWebHostEnvironment ,因此请记住。 另一个像[DisplayName("Dashboard")] [Authorize(policy: "HasAccess")]这样的middlewareactionFilter保持不变,您可以在program.cs文件中注册为app.UseMiddleware<AutoTimerMiddleware>() 你可以参考这里

测试用户简介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 文件:我在这里看到你的cspros有很多参考资料,但没有相应地分享。 所以我只解释了强制迁移相关的参考。

在此处输入图像描述

<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>

注意:请注意,您应该从 Nuget package 管理器下载EntityFrameworkCore.RelationalEntityFrameworkCore.SqlServer以进行基本迁移。

Output:

在此处输入图像描述

重要的:

  1. 一个简单但重要的提示,任何与 2.1 中的ConfigureServices相关的内容都必须放在 Asp.net Core 6 program.cs文件的var app = builder.Build()之上,并且

  2. 2.1 的public void Configure中的任何内容都必须放在app.Run()之上,或者我们可以在var app = builder.Build()之后说。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM