ASP.NET Core 6 MVC添加IdentityRole后MapRazorPages报错求助
问题解决:添加IdentityRole后MapRazorPages报错
问题原因
AddDefaultIdentity<IdentityUser>()是ASP.NET Core封装的快捷方法,内部已自动注册Razor Pages所需的依赖服务;而AddIdentity<IdentityUser, IdentityRole>()是更底层的Identity注册方式,仅负责核心身份验证逻辑,不会自动包含Razor Pages的服务注册,因此会触发找不到服务的错误。
解决步骤
补充Razor Pages服务注册
在Program.cs的服务配置段,调用AddIdentity之后,添加services.AddRazorPages();,手动注册Razor Pages所需的全部依赖。确认中间件顺序
确保中间件管道中,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
相关产品推荐
相关产品推荐

