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

时间:2016-02-23 12:11:51

标签: asp.net asp.net-core asp.net-identity-3

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

User.Identity.GetUserId();

但它似乎不再可用了。

还有类似的东西:

User.GetUserId();

但它始终返回null,即使User.Identity.IsAuthenticated in true和User.Identity.Name设置正确。

我应该用它做什么?

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

6 个答案:

答案 0 :(得分:10)

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

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应映射到userid

答案 1 :(得分:7)

@Joe Audette

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

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

detail on github

答案 2 :(得分:6)

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

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

// ClaimsIdentity identity = new ClaimsIdentity...

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);

答案 3 :(得分:0)

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

httpContext.User.Identity.IsAuthenticated ? 
    httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value 
    : Guid.Empty.ToString()

答案 4 :(得分:-1)

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

答案 5 :(得分:-3)

您也可以使用

User.Identity.Name;

有关详细信息,请转到MSDN

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

相关问题