.NET Core 6 WebAPI默认页面切换至Identity登录页及依赖注入错误排查
核心问题
错误根源在于Identity脚手架生成的登录页面模型(LoginModel)依赖默认的SignInManager<IdentityUser>,但你的项目注册的是自定义用户类型AppUser对应的SignInManager<AppUser>,两者类型不匹配,导致依赖注入容器无法解析服务。
解决步骤
1. 修正Program.cs中的Identity服务注册
确保注册Identity服务时,明确指定自定义用户类型AppUser和角色类型IdentityRole<int>(适配你使用的int类型主键)。
找到Program.cs中注册Identity的代码(无则添加),替换为以下内容:
// 注册Identity服务,绑定自定义用户与角色类型 builder.Services.AddIdentity<AppUser, IdentityRole<int>>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); // 保留你已有的Cookie配置 builder.Services.ConfigureApplicationCookie(options => { options.LoginPath = $"/Identity/Account/Login"; options.LogoutPath = $"/Identity/Account/Logout"; options.AccessDeniedPath = $"/Identity/Account/AccessDenied"; });
2. 修改LoginModel的依赖类型
找到项目中Areas/Identity/Pages/Account/Login.cshtml.cs文件,将注入的SignInManager和UserManager泛型类型从IdentityUser改为AppUser:
修改前:
private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; public LoginModel(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager, ILogger<LoginModel> logger) { _signInManager = signInManager; _userManager = userManager; _logger = logger; }
修改后:
private readonly SignInManager<AppUser> _signInManager; private readonly UserManager<AppUser> _userManager; public LoginModel(SignInManager<AppUser> signInManager, UserManager<AppUser> userManager, ILogger<LoginModel> logger) { _signInManager = signInManager; _userManager = userManager; _logger = logger; }
3. 同步其他Identity页面模型
对Account目录下的其他页面模型(如Register.cshtml.cs、ForgotPassword.cshtml.cs等)执行同样操作,将所有SignInManager<IdentityUser>、UserManager<IdentityUser>替换为对应的AppUser泛型版本。
4. 设置默认页面(补充)
若尚未完成默认页面跳转配置,在Program.cs中添加以下代码,将根路径重定向到登录页:
app.MapGet("/", context => { context.Response.Redirect("/Identity/Account/Login"); return Task.CompletedTask; });
额外说明
你自定义了AppUser(继承IdentityUser<int>)和AppDbContext(继承IdentityDbContext<AppUser, IdentityRole<int>, int>),整个Identity体系必须基于自定义类型构建,不能混用默认的IdentityUser类型,否则会持续出现服务解析失败问题。
内容的提问来源于stack exchange,提问作者Huy Hoang Nguyen

