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

AspNetCore Identity下AuthenticationStateProvider获取UserID为空如何取sub值

错误原因

你原有代码的匹配逻辑有误:你用c.Type.Equals(user.Identity.Name)作为Claim筛选条件,相当于要求Claim的类型属性等于当前用户名的字符串值,完全混淆了Claim的类型和值的用途,自然匹配不到存储用户ID的Claim,所以返回空值。

解决方案

根据你输出的Claims列表,用户ID存储在sub类型的Claim中,有两种写法可以正确获取:

var authState = await ASP.GetAuthenticationStateAsync();
var user = authState.User;

// 写法1:直接匹配sub类型
var userId = user.FindFirst(c => c.Type == "sub")?.Value;

// 写法2(更推荐):使用.NET内置常量,不需要硬写字符串,避免拼写错误
// var userId = user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

说明:System.Security.Claims.ClaimTypes.NameIdentifier是.NET内置的常量,对应OpenID Connect标准里的sub字段,专门用于存储用户的唯一标识,兼容性更好。

获取到的userId就是你需要的用户ID值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:45:01