如何在 .NET Core 2.0 中获取登录用户的用户 ID? [英] How to get user id of logged in user in .NET Core 2.0?

查看:43
本文介绍了如何在 .NET Core 2.0 中获取登录用户的用户 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .NET Core 和 MVC 创建了一个 angular 2 应用程序.我想知道用户的登录 ID.如何在 .net core 中获取用户的登录 ID?

I have created a angular 2 application using .NET Core and MVC. I want to know the login id of user. How to get logged in id of a user in .net core?

这是我的第一个 Angular 应用程序.我使用以下链接开始https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

This is my first angular application. I used following link to start https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

我想使用 Windows 身份验证,在控制器中获取登录 ID.

I want to use windows authentication, to get login id in a controller.

推荐答案

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

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);

这篇关于如何在 .NET Core 2.0 中获取登录用户的用户 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆