You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ASP.NET MVC Core 2.1项目升级至ASP.NET MVC Core 6?

ASP.NET Core 2.1 升级至 ASP.NET Core 6.0 代码修改方案

一、csproj NuGet 包配置修改

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <NoWin32Manifest>true</NoWin32Manifest>
    <UserSecretsId>*******************</UserSecretsId>
    <ServerGarbageCollection>false</ServerGarbageCollection>
    <!-- Core 6.0 已默认启用 Razor 编译,无需单独配置 -->
  </PropertyGroup>

  <ItemGroup>
    <!-- 第三方包更新至兼容.NET 6的版本 -->
    <PackageReference Include="BCrypt-Core" Version="2.0.0" />
    <PackageReference Include="ClosedXML" Version="0.102.1" />
    <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="13.6.0" />
    <!-- EF Core 升级至6.0版本 -->
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.25">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.25" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.25">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <!-- 代码生成工具升级 -->
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.16" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.1" />
    <PackageReference Include="System.Linq.Dynamic.Core" Version="1.3.0" />
    <!-- Core 6.0 SDK已包含ASP.NET Core基础组件,无需单独引用 -->
  </ItemGroup>
</Project>

二、Program.cs 重构(合并Startup逻辑)

var builder = WebApplication.CreateBuilder(args);

// 注册服务
var connection = builder.Configuration.GetConnectionString("DBconnection");
builder.Services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Logins/UserLogin/";
        options.AccessDeniedPath = "/AccessDenied";
        options.ExpireTimeSpan = TimeSpan.FromHours(10);
    });

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

// 添加MVC服务
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 配置中间件
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();

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

app.Run();

三、HomeController 修改

[DisplayName("Dashboard")]
[Authorize(policy: "HasAccess")]
public class HomeController : BaseController
{
    private readonly IMvcControllerDiscovery _mvcControllerDiscovery;
    // Core 3.0+ 已将IHostingEnvironment替换为IWebHostEnvironment
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(HoshmandDBContext context, IWebHostEnvironment webHostEnvironment) : base(context)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    public IActionResult Index(DateTime? date = null)
    {
        date = date ?? GetLocalDateTime();
        ViewBag.date = date;
        // 补全返回语句
        return View();
    }
}

四、LoginsController 优化

public class LoginsController : BaseController
{
    public LoginsController(HoshmandDBContext context) : base(context)
    {
    }

    [HttpGet]
    // 无异步操作时无需强行使用Task.Run,直接返回View即可
    public IActionResult UserLogin()
    {
        return View(new Login());
    }
}

内容的提问来源于stack exchange,提问作者Hedayat Hoshmand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:20:35