C# 使用 Claims 获取用户ID和用户名
在这段代码中,您正在尝试从 HttpContext.User 中获取一个名为'Name'的声明。但在上面的代码中,并没有将'Name'声明添加到荷载信息中。您添加了一个名为'NameIdentifier'的声明,用于存储用户ID,以及一个名为'Name'的声明,用于存储用户名称。因此,如果要使用这些声明,您需要从 HttpContext.User 中获取相应的声明类型,如下所示:
var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
int userId = int.Parse(userIdClaim.Value);
Console.WriteLine($'{userId}');
// 使用userId进行后续的操作
}
var userNameClaim = HttpContext.User.FindFirst(ClaimTypes.Name);
if (userNameClaim != null)
{
string userName = userNameClaim.Value;
Console.WriteLine($'{userName}');
// 使用userName进行后续的操作
}
这样,您就可以分别获取用户ID和用户名的声明,并在后续操作中使用它们。
原文地址: https://www.cveoy.top/t/topic/mXoL 著作权归作者所有。请勿转载和采集!