在ASP.NET Core 2中获取用户ID [英] Get user id in ASP.NET Core 2

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

问题描述

我正在尝试获取ASP.NET Core 2.1 MVC项目中的用户ID.

I'm trying to get the user id in an ASP.NET Core 2.1 MVC project.

但是,我只能收到电子邮件.我几乎可以肯定必须有1/2线的方式才能获得它(在ASP.NET MVC成员资格中,它只是var loggingInUserId = User.Identity.GetUserId();

However, I was only able to get the email. I'm almost sure there has to be a 1/2 line way to get it (in the ASP.NET MVC membership it was just var loggedInUserId = User.Identity.GetUserId();

到目前为止,我一直这样尝试:

I tried so far like this:

 var loggedInUserId = User.Identity.ToString();    // Result = Name (E-mail) 
 //  var loggedInUserId = User.Identity.Name;    // Result (E-mail)

&这就是我现在需要的

& this is now what I need

推荐答案

User.Identity.GetUserId()的旧方法不再存在,但可以将ID作为对您的委托人即User的要求.您可以通过多种方式进行操作:

The old method of User.Identity.GetUserId() no longer exists, but the id is available as a claim on your principal, i.e. User. There's a number of ways you can get to it:

  1. 第一个也是最简单的方法就是提出声明:

  1. The first and easiest is just pull out the claim:

var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

  • 如果您已经有一个UserManager<TUser>实例(或想要注入一个实例),则可以在该实例上使用GetUserId()方法:

  • If you already have an instance of UserManager<TUser> (or want to inject one), then you can use the GetUserId() method on that:

    var userId = _userManager.GetUserId(User);
    

  • 最后,如果您想使用旧的方法,就像将扩展名添加到ClaimsPrincipal并利用上面的第一种方法一样简单:

  • Finally, if you want the old way back, it's as simple as adding an extension to ClaimsPrincipal and utilize the first method above:

    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal) =>
            principal.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    

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

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