You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET/Blazor Server中获取当前已认证用户的BrandId自定义属性

实现步骤

首先确保你项目的基础配置正确:

  1. 注册Identity时使用你自定义的ApplicationUser类,而非默认的IdentityUser
  2. ApplicationDbContext继承IdentityDbContext<ApplicationUser>,已完成自定义字段的数据库迁移

方案1:直接在Index页面实现

第一步:注入所需服务

在Index.razor顶部添加注入声明:

@inject AuthenticationStateProvider AuthStateProvider
@inject UserManager<ApplicationUser> UserManager

第二步:添加获取BrandId的逻辑

在页面的@code代码块中添加如下逻辑:

private int _currentBrandId;

protected override async Task OnInitializedAsync()
{
    // 获取当前用户认证状态
    var authState = await AuthStateProvider.GetAuthenticationStateAsync();
    var claimsPrincipal = authState.User;

    // 仅当用户已认证时查询属性
    if (claimsPrincipal.Identity?.IsAuthenticated == true)
    {
        var currentAppUser = await UserManager.GetUserAsync(claimsPrincipal);
        if (currentAppUser != null)
        {
            _currentBrandId = currentAppUser.BrandId;
        }
    }
}

之后你可以直接在页面渲染部分使用_currentBrandId变量。

方案2:封装为通用服务(多页面复用推荐)

如果多个页面都需要用到当前用户的自定义属性,建议把逻辑封装成公共服务,避免重复代码:

第一步:定义服务接口与实现

public interface ICurrentUserService
{
    Task<ApplicationUser?> GetCurrentAuthenticatedUserAsync();
}

public class CurrentUserService : ICurrentUserService
{
    private readonly AuthenticationStateProvider _authStateProvider;
    private readonly UserManager<ApplicationUser> _userManager;

    public CurrentUserService(AuthenticationStateProvider authStateProvider, UserManager<ApplicationUser> userManager)
    {
        _authStateProvider = authStateProvider;
        _userManager = userManager;
    }

    public async Task<ApplicationUser?> GetCurrentAuthenticatedUserAsync()
    {
        var authState = await _authStateProvider.GetAuthenticationStateAsync();
        if (authState.User.Identity?.IsAuthenticated != true)
        {
            return null;
        }
        return await _userManager.GetUserAsync(authState.User);
    }
}

第二步:注册服务

在Program.cs中添加服务注册:

builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

第三步:在Index页面使用

@inject ICurrentUserService CurrentUserService
private int _currentBrandId;

protected override async Task OnInitializedAsync()
{
    var currentUser = await CurrentUserService.GetCurrentAuthenticatedUserAsync();
    if (currentUser != null)
    {
        _currentBrandId = currentUser.BrandId;
    }
}
注意事项
  • 如果Index页面已经添加了[Authorize]特性限制仅登录用户访问,可跳过用户是否认证的判断,仍建议保留空值判断避免异常
  • 不要在同步生命周期方法中调用上述异步逻辑,避免出现死锁问题
  • 首次添加自定义字段后需要执行EF Core迁移更新数据库,否则查询不到对应属性值

内容的提问来源于stack exchange,提问作者viac92

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:36:03