Select Page
This entry has been published on 2017-03-08 and may be out of date.

Last Updated on 2017-03-08.

[:en]Using Microsoft.AspNetCore.Identity, you might miss a method like GetUserId() which was available for previous .NET frameworks by default.

As a workaround, use this extension method:

using System.Security.Claims;

namespace myproject.Common
{
    public static class ExtensionMethods
    {
        /// <summary>
        /// User ID
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string getUserId(this ClaimsPrincipal user)
        {
            if (!user.Identity.IsAuthenticated)
                return null;

            ClaimsPrincipal currentUser = user;
            return currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
        }

    }
}

Usage:

using myproject.Common;

...

var userId = User.getUserId();

 [:]