Proper way to get current User ID in Entity Framework Core

后端 未结 4 851
灰色年华
灰色年华 2021-02-07 01:56

There are a bunch of different answers floating around here for the different RC\'s of ASP.NET Core on how to get the ID of the currently logged in user. I wanted to ask the def

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 02:48

    If you are accessing this from withing the Controller, then using UserManager to get the user ID is pretty inefficient as you are making a round trip to the database. If you are using ClaimsIdentity, you can do something like this to get the user id:

    var claimsIdentity = (ClaimsIdentity)this.User.Identity;
    var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
    var userId = claim.Value;
    

    This method just reads the user ID which is already present in the cookie, which in turn is automatically deserialized and stored in a ClaimsIdentity instance.

    I use this helper class:

    public static class UserHelpers
    {
        public static string GetUserId(this IPrincipal principal)
        {
            var claimsIdentity = (ClaimsIdentity)principal.Identity;
            var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
            return claim.Value;
        }
    }
    

    So getting a user ID becomes:

    var userId = this.User.GetUserId();
    

    If, for some reason, the required claim is not present in the Claims colleciton, you can easily add it when creating the user's ClaimsIdentity:

    public class ApplicaionUser : IdentityUser
    {
        public async Task GenerateUserIdentityAsync(UserManager manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            userIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, this.UserId));
            return userIdentity;
        }
    }
    

提交回复
热议问题