在 ASP.NET Core 2 中获取用户 ID

编程入门 行业动态 更新时间:2024-10-17 15:33:40
本文介绍了在 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:

  • 第一个也是最简单的方法就是取消声明:

  • 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

    本文发布于:2023-11-13 22:36:51,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1585511.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:用户   NET   ASP   ID   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!