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

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

问题描述

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



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



我想使用Windows身份验证来获取控制器中的登录ID。

解决方案

这真的取决于您的应用中采用哪种身份验证。



考虑到您提到了Angular,我不确定



为了使您朝正确的方向发展,您的行动方针是从用户那里获得相关的主张。



身份。像这样:

  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



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

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


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?

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/

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.

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;

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

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天全站免登陆