1

Or do I need to set up Sessions in ASP.NET and get the user ID and pass it around manually like... ?

  public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        //Save UserId in session
        HttpContext.Session.SetString("UserIdKey", "123");
        ViewData["UserId"] = HttpContext.Session.GetString("UserIdKey");

....

punkouter
  • 4,920
  • 15
  • 64
  • 106
  • Via the `UserManager` would seem to be the way in .net Core - see [ASP.NET Core Identity - get current user](https://stackoverflow.com/questions/38751616/asp-net-core-identity-get-current-user) – SpruceMoose Apr 20 '18 at 10:36

2 Answers2

2

Assuming that you have injected a UserManager, as of 2.1 you can use:

string userid = _userManager.GetUserId(userPrincipal);

Where userPrincipal can be provided by the ControllerBase.User Property.

SpruceMoose
  • 8,885
  • 4
  • 37
  • 52
2

Use Extension

    public static class IdentityExtension
    {
        public static string GetId(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

            Claim claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            return claim.Value;
        }
    }

Example

User.Identity.GetId()
Fatih Erol
  • 581
  • 1
  • 7
  • 21