How to get current UserId in Identity 3.0? User.GetUserId returns null

流过昼夜 提交于 2019-12-04 02:50:54

Following our discussion, it seems your user identity does not contain the correct claim used by User.GetUserId().

Here is how you can manually set the NameIdentifier claim:

// ClaimsIdentity identity = new ClaimsIdentity...

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

I think there was a built in extension method for that in previous versions but they removed it. you can implement your own to replace it:

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 should map to userid

@Joe Audette

it turns out it has been move to other place.

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

detail on github

My goal was to retrieve the UserId in a custom middleware this is what I used:

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

User.Identity.GetUserId(); Is available inside a class that inherits Page.

You can also use

User.Identity.Name;

For more information go to MSDN

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!