Blazor Server应用中如何从AspNetUsers表获取当前登录用户详情
在Blazor Server中显示登录用户的员工编号(Pno)
先确认用户类扩展正确
首先要确保你的ApplicationUser类已经扩展了IdentityUser,并包含Pno属性,保证EF Core能正确映射到AspNetUsers表的对应字段:
public class ApplicationUser : IdentityUser { // 对应AspNetUsers表中的Pno列 public string Pno { get; set; } }
同时在DbContext中配置正确(如果未自动映射):
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } }
方法一:把Pno加入登录Claims(推荐,减少数据库查询)
默认的ClaimsPrincipal不会包含自定义的Pno字段,你需要将其添加到用户的Claims集合中,登录后就能直接从AuthenticationState里获取。
1. 创建自定义用户Claims工厂
新建类继承UserClaimsPrincipalFactory<ApplicationUser>:
public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser> { public CustomUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, optionsAccessor) { } protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user) { var identity = await base.GenerateClaimsAsync(user); // 将Pno添加到Claims,自定义Type名称为"Pno" identity.AddClaim(new Claim("Pno", user.Pno)); return identity; } }
2. 在Program.cs注册该工厂
替换默认的UserClaimsPrincipalFactory:
builder.Services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomUserClaimsPrincipalFactory>();
3. 在Blazor组件中获取并显示Pno
通过AuthenticationStateProvider获取用户Claims:
@page "/" @inject AuthenticationStateProvider AuthStateProvider <h3>欢迎登录</h3> @if (user != null) { <p>你的员工编号:@pno</p> } @code { private ClaimsPrincipal user; private string pno; protected override async Task OnInitializedAsync() { var authState = await AuthStateProvider.GetAuthenticationStateAsync(); user = authState.User; // 从Claims中取出Pno pno = user.FindFirstValue("Pno"); } }
方法二:直接从数据库查询用户信息(适合偶尔获取的场景)
若不想修改Claims,可通过UserManager直接查询当前登录用户的Pno:
@page "/" @inject UserManager<ApplicationUser> UserManager @inject AuthenticationStateProvider AuthStateProvider <h3>欢迎登录</h3> @if (currentUser != null) { <p>你的员工编号:@currentUser.Pno</p> } @code { private ApplicationUser currentUser; protected override async Task OnInitializedAsync() { var authState = await AuthStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { currentUser = await UserManager.GetUserAsync(user); } } }
注意事项
- 确保注册时已将用户输入的员工编号正确保存到
ApplicationUser.Pno属性中 - 使用方法一时,修改Claims后需要用户重新登录才能生效
内容的提问来源于stack exchange,提问作者abraKajapa
相关产品推荐
相关产品推荐

