如何在Identity 3.0中获取当前的UserId?User.GetUserId返回null

Pio*_*rek 9 asp.net asp.net-identity-3 asp.net-core

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

User.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)

但它似乎不再可用了.

还有类似的东西:

User.GetUserId();
Run Code Online (Sandbox Code Playgroud)

但它始终返回null,即使正确设置了User.Identity.IsAuthenticated并且正确设置了User.Identity.Name.

我应该用它做什么?

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

Joe*_*tte 12

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

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ClaimType.NameIdentifier应映射到userid


max*_*sam 7

@Joe Audette

事实证明它已经转移到其他地方.

User.GetUserId => UserManager.GetUserId(User)
User.GetUserName => UserManager.GetUserName(User)
User.IsSignedIn => SignInManager.IsSignedIn(User)
Run Code Online (Sandbox Code Playgroud)

github上的详细信息


Hez*_*zye 6

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

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

// ClaimsIdentity identity = new ClaimsIdentity...

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);
Run Code Online (Sandbox Code Playgroud)