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

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

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

    发布评论

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

    >www.elefans.com

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