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

@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


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