13

我需要获取提出某些请求的用户的 ID。在以前的 Identity 版本中,我可以这样做:

User.Identity.GetUserId();

但它似乎不再可用。

还有类似的东西:

User.GetUserId();

但它总是返回 null,即使 User.Identity.IsAuthenticated 为 true 并且 User.Identity.Name 设置正确。

我应该用什么来做到这一点?

编辑:我的身份验证逻辑基于[默认 Visual Studio 2015 模板],到目前为止我的身份没有太大变化,所以如果你想检查它是如何完成的,你可以在我粘贴的 github 链接上简单地看到它。

4

6 回答 6

19

我认为在以前的版本中有一个内置的扩展方法,但他们删除了它。您可以实现自己的来替换它:

using System;
using System.Security.Claims;
using Microsoft.AspNet.Identity;

namespace cloudscribe.Core.Identity
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }
            var claim = principal.FindFirst(ClaimTypes.NameIdentifier);
            return claim != null ? claim.Value : null;
        }
    }
}

ClaimType.NameIdentifier 应该映射到用户 ID

于 2016-02-23T12:31:39.440 回答
10

@乔·奥德特

原来它已经搬到其他地方了。

User.GetUserId => UserManager.GetUserId(User)
User.GetUserName => UserManager.GetUserName(User)
User.IsSignedIn => SignInManager.IsSignedIn(User)

github上的详细信息

于 2016-06-02T20:47:01.830 回答
9

根据我们的讨论,您的用户身份似乎不包含 User.GetUserId() 使用的正确声明。

以下是手动设置 NameIdentifier 声明的方法:

// ClaimsIdentity identity = new ClaimsIdentity...

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);
于 2016-02-28T13:59:02.987 回答
0

我的目标是在自定义中间件中检索 UserId,这就是我使用的:

httpContext.User.Identity.IsAuthenticated ? 
    httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value 
    : Guid.Empty.ToString()
于 2019-08-08T20:32:37.943 回答
-2

User.Identity.GetUserId();在继承的类中可用Page

于 2016-02-23T12:37:45.387 回答
-3

你也可以使用

User.Identity.Name;

欲了解更多信息,请访问 MSDN

https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx

于 2016-02-23T13:19:18.053 回答