且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 .NET Core 2.0 中获取登录用户的用户 ID?

更新时间:2021-12-15 08:15:21

这实际上取决于您在应用中使用的身份验证类型.

That really depends on what kind of authentication you have in your app.

考虑到您提到了 Angular,我不确定您用于身份验证的框架以及您的设置.

Considering you mentioned Angular, I'm not sure what framework you use for authentication, and what are your settings.

为了让您朝着正确的方向前进,您的行动方针是从用户身份获取相关声明.像这样:

To get you moving into the right direction, your course of action would be getting the relevant claim from the user identity. Something like this:

var ident = User.Identity as ClaimsIdentity;
var userID = ident.Claims.FirstOrDefault(c => c.Type == idClaimType)?.Value;

其中 idClaimType 是存储您的身份的声明的类型.根据框架的不同,它通常是
ClaimTypes.NameIdentifier (= "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")

JwtClaimTypes.Subject (="sub")

where idClaimType is the type of the claim that stores your Identity. Depending on the framework, it would usually either be
ClaimTypes.NameIdentifier (= "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
or
JwtClaimTypes.Subject (= "sub")

如果您使用的是 Asp.Net Core Identity,您可以在 UserManager 上使用他们的辅助方法来简化对它的访问:

If you're using Asp.Net Core Identity, you could use their helper method on the UserManager to simplify access to it:

UserManager<ApplicationUser> _userManager;
[…]
var userID = _userManager.GetUserId(User);