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

添加Identity后ASP.NET Core 6 MVC视图无法映射的问题求助

ASP.NET Core 6 MVC添加Identity后视图404问题解决

问题根源:中间件执行顺序错误

你的代码中存在两处关键问题导致MVC路由无法正常匹配:

  • app.MapRazorPages()被放在了路由初始化之前,破坏了请求处理流程
  • UseAuthentication()后多了一个冗余分号,可能导致中间件链异常

修正后的完整Program.cs代码

var builder = WebApplication.CreateBuilder(args);

// 注册服务
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<AppDbContext>(option => option.UseSqlServer(
    builder.Configuration.GetConnectionString("DefaultConnection")
));

// 添加Identity服务,附带默认UI支持(可选,确保Identity页面正常加载)
builder.Services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultUI();

builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

var app = builder.Build();
 
// 配置请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

// 先初始化路由系统
app.UseRouting();

// 认证、授权中间件必须在路由之后,端点映射之前
app.UseAuthentication();
app.UseAuthorization();

// 先映射Razor Pages端点,再处理MVC控制器路由
app.MapRazorPages();

app.MapControllerRoute(
    name: "default",
    pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");

app.Run();

核心修正说明

  1. 调整中间件顺序:UseRouting()必须在所有端点映射(MapRazorPages()、MapControllerRoute())之前执行,确保路由系统先完成初始化。
  2. 修复语法错误:移除UseAuthentication();;中的多余分号,保证中间件链正常执行。
  3. 添加AddDefaultUI():如果需要使用Identity自带的注册、登录等页面,这个方法会自动引入对应的UI资源,避免页面缺失。
  4. 端点映射顺序:先注册Razor Pages端点,再注册MVC控制器路由,避免路由匹配优先级冲突。

验证方法

  1. 替换代码后重启项目
  2. 访问原MVC视图路径(如/Home/Index),确认404错误消失
  3. 访问Identity页面(如/Identity/Account/Login),验证身份验证功能正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:27:33