如何在同一项目中同时使用IdentityApiEndpoints与Razor Pages默认Identity UI?
问题场景
需要在同一ASP.NET Core项目中同时启用Identity API端点和Razor Pages身份验证UI,但在Program.cs中添加AddIdentityApiEndpoints<MyCustomUser>()后,应用启动时抛出认证方案重复的错误。
出错的配置代码
builder.Services.AddDbContext<MyCustomDbContext>(options => options.UseNpgsql(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); services.AddDefaultIdentity<MyCustomUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<MyCustomRole>() .AddEntityFrameworkStores<MyCustomDbContext>(); // 注释掉该行后应用可正常运行 services.AddIdentityApiEndpoints<MyCustomUser>();
错误信息
System.InvalidOperationException: Scheme already exists: Identity.Application
at Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(String name, Action1 configureBuilder) at Microsoft.Extensions.Options.ConfigureNamedOptions1.Configure(String name, TOptions options)
at Microsoft.Extensions.Options.OptionsFactory1.Create(String name) at Microsoft.Extensions.Options.UnnamedOptionsManager1.get_Value()
解决方案
问题出在AddDefaultIdentity与AddIdentityApiEndpoints会重复注册Identity.Application认证方案,导致冲突。改用AddIdentity配置核心Identity服务,再分别添加UI和API端点支持即可解决:
修正后的配置代码
builder.Services.AddDbContext<MyCustomDbContext>(options => options.UseNpgsql(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // 使用AddIdentity替代AddDefaultIdentity,避免重复注册认证方案 builder.Services.AddIdentity<MyCustomUser, MyCustomRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<MyCustomDbContext>() .AddDefaultTokenProviders() .AddDefaultUI(); // 启用Razor Pages Identity UI // 添加Identity API端点支持 builder.Services.AddIdentityApiEndpoints<MyCustomUser>() .AddEntityFrameworkStores<MyCustomDbContext>(); // 映射Identity API路由与Razor Pages路由 app.MapIdentityApi<MyCustomUser>(); app.MapRazorPages();
核心说明
AddIdentity是底层的Identity服务注册方法,不会自动绑定UI或API端点,避免了方案重复问题。- 通过
AddDefaultUI()显式启用Razor Pages身份验证UI。 - 调用
AddIdentityApiEndpoints()添加API端点支持后,必须通过MapIdentityApi<MyCustomUser>()完成路由映射。
内容的提问来源于stack exchange,提问作者Hamid Z

