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

ASP.NET Core 6 MVC添加IdentityRole后MapRazorPages报错求助

问题解决:添加IdentityRole后MapRazorPages报错

问题原因

AddDefaultIdentity<IdentityUser>()是ASP.NET Core封装的快捷方法,内部已自动注册Razor Pages所需的依赖服务;而AddIdentity<IdentityUser, IdentityRole>()是更底层的Identity注册方式,仅负责核心身份验证逻辑,不会自动包含Razor Pages的服务注册,因此会触发找不到服务的错误。

解决步骤

  1. 补充Razor Pages服务注册
    在Program.cs的服务配置段,调用AddIdentity之后,添加services.AddRazorPages();,手动注册Razor Pages所需的全部依赖。

  2. 确认中间件顺序
    确保中间件管道中,UseAuthentication()和UseAuthorization()在MapRazorPages()之前执行,且UseRouting()已正确配置(这是路由映射的前提)。

修改后的完整代码示例

var builder = WebApplication.CreateBuilder(args);

// 注册数据库上下文
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 注册带角色支持的Identity服务
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

// 手动添加Razor Pages服务(关键修复)
builder.Services.AddRazorPages();

var app = builder.Build();

// 环境相关错误处理配置
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

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

app.UseRouting();

// 身份验证与授权中间件需在路由映射前启用
app.UseAuthentication();
app.UseAuthorization();

// 映射Razor Pages路由
app.MapRazorPages();

app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:32:39