如何在.NET 8 IdentityCore中注册UserManager?Blazor Server报错解决
Blazor Server (.NET 8) 独立账户用户管理注入错误解决
错误信息
InvalidOperationException: 无法为类型'StoreManagement.Components.Pages.Users.Users'上的属性'_UserManager'提供值。未注册类型'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'的服务。
问题代码
Users.razor
@page "/users" @using Microsoft.AspNetCore.Authorization; @using Microsoft.AspNetCore.Identity; @inject UserManager<IdentityUser> _UserManager @inject RoleManager<IdentityRole> _RoleManager @inject AuthenticationStateProvider AuthenticationStateProvider <h3>Administration</h3> <AuthorizeView> <Authorized> @if (@context.User.IsInRole(ADMINISTRATION_ROLE)) { <p>You are in @ADMINISTRATION_ROLE </p> } else { <p>You're not signed in as a user in @ADMINISTRATION_ROLE.</p> } </Authorized> <NotAuthorized> <p>You're not loggged in.</p> </NotAuthorized> </AuthorizeView> @code { [CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; } string ADMINISTRATION_ROLE = "Admin"; System.Security.Claims.ClaimsPrincipal CurrentUser; protected override async Task OnInitializedAsync() { var RoleResult = await _RoleManager.FindByNameAsync(ADMINISTRATION_ROLE); if (RoleResult == null) { await _RoleManager.CreateAsync(new IdentityRole(ADMINISTRATION_ROLE)); } var user = await _UserManager.FindByEmailAsync("exapmle@gmail.com"); if (user != null) { var UserResult = await _UserManager.IsInRoleAsync(user, ADMINISTRATION_ROLE); if (!UserResult) { // Put admin in Administrator role await _UserManager.AddToRoleAsync(user, ADMINISTRATION_ROLE); } } CurrentUser = (await authenticationStateTask).User; } }
Program.cs
using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using StoreManagement.Components; using StoreManagement.Components.Account; using StoreManagement.Data; using StoreManagement.Services; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); builder.Services.AddCascadingAuthenticationState(); builder.Services.AddScoped<IdentityUserAccessor>(); builder.Services.AddScoped<IdentityRedirectManager>(); builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>(); builder.Services.AddAuthentication(options => { options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultSignInScheme = IdentityConstants.ExternalScheme; }) .AddIdentityCookies(); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddSignInManager() .AddDefaultTokenProviders(); builder.Services.AddSingleton<IEmailSender<ApplicationUser>, EmailSender>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAntiforgery(); app.MapRazorComponents<App>() .AddInteractiveServerRenderMode(); // Add additional endpoints required by the Identity /Account Razor components. app.MapAdditionalIdentityEndpoints(); app.Run();
解决步骤
错误核心是类型不匹配:Program.cs中注册的是UserManager<ApplicationUser>,但组件中注入的是UserManager<IdentityUser>,DI容器找不到对应的服务实例。
- 修正组件中的注入类型
将Users.razor中的注入代码修改为:
@inject UserManager<ApplicationUser> _UserManager
- 确保自定义用户类继承正确
确认ApplicationUser类继承自IdentityUser:
using Microsoft.AspNetCore.Identity; namespace StoreManagement.Data; public class ApplicationUser : IdentityUser { // 可添加自定义属性 }
- 修正代码拼写错误
exapmle@gmail.com改为example@gmail.comloggged改为logged
内容的提问来源于stack exchange,提问作者Noctious
相关产品推荐
相关产品推荐

