How to get the current logged in user ID in ASP.NET Core? How to get the current logged in user ID in ASP.NET Core? asp.net asp.net

How to get the current logged in user ID in ASP.NET Core?


Update in ASP.NET Core Version >= 2.0

In the Controller:

public class YourControllerNameController : Controller{    private readonly UserManager<ApplicationUser> _userManager;        public YourControllerNameController(UserManager<ApplicationUser> userManager)    {        _userManager = userManager;    }    public async Task<IActionResult> YourMethodName()    {        var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId        var userName =  User.FindFirstValue(ClaimTypes.Name) // will give the user's userName                // For ASP.NET Core <= 3.1        ApplicationUser applicationUser = await _userManager.GetUserAsync(User);        string userEmail = applicationUser?.Email; // will give the user's Email       // For ASP.NET Core >= 5.0       var userEmail =  User.FindFirstValue(ClaimTypes.Email) // will give the user's Email    }}

In some other class:

public class OtherClass{    private readonly IHttpContextAccessor _httpContextAccessor;    public OtherClass(IHttpContextAccessor httpContextAccessor)    {       _httpContextAccessor = httpContextAccessor;    }   public void YourMethodName()   {      var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);   }}

Then you should register IHttpContextAccessor in the Startup class as follows:

public void ConfigureServices(IServiceCollection services){    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();    // Or you can also register as follows    services.AddHttpContextAccessor();}

For more readability write extension methods as follows:

public static class ClaimsPrincipalExtensions{    public static T GetLoggedInUserId<T>(this ClaimsPrincipal principal)    {        if (principal == null)            throw new ArgumentNullException(nameof(principal));        var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);        if (typeof(T) == typeof(string))        {            return (T)Convert.ChangeType(loggedInUserId, typeof(T));        }        else if (typeof(T) == typeof(int) || typeof(T) == typeof(long))        {            return loggedInUserId != null ? (T)Convert.ChangeType(loggedInUserId, typeof(T)) : (T)Convert.ChangeType(0, typeof(T));        }        else        {            throw new Exception("Invalid type provided");        }    }    public static string GetLoggedInUserName(this ClaimsPrincipal principal)    {        if (principal == null)            throw new ArgumentNullException(nameof(principal));        return principal.FindFirstValue(ClaimTypes.Name);    }    public static string GetLoggedInUserEmail(this ClaimsPrincipal principal)    {        if (principal == null)            throw new ArgumentNullException(nameof(principal));        return principal.FindFirstValue(ClaimTypes.Email);    }}

Then use as follows:

public class YourControllerNameController : Controller{    public IActionResult YourMethodName()    {        var userId = User.GetLoggedInUserId<string>(); // Specify the type of your UserId;        var userName = User.GetLoggedInUserName();        var userEmail = User.GetLoggedInUserEmail();    }}public class OtherClass{     private readonly IHttpContextAccessor _httpContextAccessor;     public OtherClass(IHttpContextAccessor httpContextAccessor)     {         _httpContextAccessor = httpContextAccessor;     }     public void YourMethodName()     {         var userId = _httpContextAccessor.HttpContext.User.GetLoggedInUserId<string>(); // Specify the type of your UserId;     }}


Until ASP.NET Core 1.0 RC1 :

It's User.GetUserId() from System.Security.Claims namespace.

Since ASP.NET Core 1.0 RC2 :

You now have to use UserManager.You can create a method to get the current user :

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

And get user information with the object :

var user = await GetCurrentUserAsync();var userId = user?.Id;string mail = user?.Email;

Note :You can do it without using a method writing single lines like this string mail = (await _userManager.GetUserAsync(HttpContext.User))?.Email, but it doesn't respect the single responsibility principle. It's better to isolate the way you get the user because if someday you decide to change your user management system, like use another solution than Identity, it will get painful since you have to review your entire code.


you can get it in your controller:

using System.Security.Claims;var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

or write an extension method like before .Core v1.0

using System;using System.Security.Claims;namespace Shared.Web.MvcExtensions{    public static class ClaimsPrincipalExtensions    {        public static string GetUserId(this ClaimsPrincipal principal)        {            if (principal == null)                throw new ArgumentNullException(nameof(principal));            return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;        }    }}

and get wherever user ClaimsPrincipal is available :

using Microsoft.AspNetCore.Mvc;using Shared.Web.MvcExtensions;namespace Web.Site.Controllers{    public class HomeController : Controller    {        public IActionResult Index()        {            return Content(this.User.GetUserId());        }    }}