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

查看:32
本文介绍了在 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 的实例(或者想要注入一个),那么你可以使用 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天全站免登陆