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

如何在.NET 5的Blazor Server项目中获取已登录用户的UserId

问题原因
  • 你代码中查找Claim用的类型字符串填写错误,ASP.NET Core Identity默认存储的用户ID对应的Claim类型不是纯字符串nameidentifier,而是带标准命名空间的完整URI,直接使用系统提供的枚举ClaimTypes.NameIdentifier即可正确匹配。
  • 如果你的Blazor Server项目开启了预渲染(Prerender),预渲染阶段身份认证状态还未完成初始化,也会导致获取结果为null。
正确实现方案

方式1:通过级联参数获取(官方推荐)

Blazor Server默认会将Task<AuthenticationState>作为级联参数向下传递,直接在组件内声明即可,不需要手动注入AuthenticationStateProvider:

// 组件代码顶部声明级联参数
[CascadingParameter]
private Task<AuthenticationState> AuthStateTask { get; set; }

protected override async Task OnInitializedAsync()
{
    var authState = await AuthStateTask;
    if (authState.User.Identity?.IsAuthenticated == true)
    {
        // 直接使用系统定义的ClaimTypes枚举,无需手写匹配字符串
        var userId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
        // 此处userId即为需要的已登录用户ID
    }
}

方式2:基于你现有代码修改

将查找Claim的匹配条件替换为ClaimTypes.NameIdentifier即可:

var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
if (authState.User.Identity.IsAuthenticated)
{
    var id = authState.User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
}
预渲染场景额外处理

如果你在_Host.cshtml中使用的是render-mode="ServerPrerendered"预渲染模式,需要做任意一种调整避免取空:

  • 将渲染模式改为render-mode="Server"关闭预渲染
  • 将获取用户ID的逻辑移到OnAfterRenderAsync生命周期中,等首次渲染完成后执行:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var authState = await AuthStateTask;
        if (authState.User.Identity?.IsAuthenticated == true)
        {
            var userId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            // 拿到userId后执行后续逻辑
            StateHasChanged();
        }
    }
}
注意事项

如果你的组件允许未授权访客访问,一定要先判断IsAuthenticated为true再读取Claim值,避免出现空引用异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:15:07