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
  • 5,170
  • 15
  • 71
  • 116
  • 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
  • 9,737
  • 4
  • 39
  • 53
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
  • 633
  • 2
  • 8
  • 22