Proper way to get current User ID in Entity Framework Core

后端 未结 4 854
灰色年华
灰色年华 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:57

    You can get UserId by this way also.

    public class Program
       {
               private readonly SignInManager _signInManager;
    
               public Program(SignInManager signInManager)
               {
                   _signInManager = signInManager;
                  var UserId = _signInManager.Context.User.Claims.FirstOrDefault().Value;
               }
       }
    

    Where ApplicationUser class is given below....

    public class ApplicationUser:IdentityUser
        {
            [Column(TypeName = "Nvarchar(500)")]
            public string FirstName { get; set; }
            [Column(TypeName = "Nvarchar(500)")]
            public string MiddleName { get; set; }
            [Column(TypeName = "Nvarchar(500)")]
            public string LastName { get; set; }
            [Column(TypeName = "DateTime")]
            public DateTime? LastAccess { get; set; }
        }
    

    And Your ApplicationUser class should inherited by IdentityUser.

提交回复
热议问题