Get property of applicationuser from the asp.net core identity

前端 未结 1 1381
遥遥无期
遥遥无期 2021-01-14 11:33

I found this link:

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

But the answers are all OUTDATED!

And this SO post can not neither be a solu

相关标签:
1条回答
  • 2021-01-14 11:38

    For the controller, have a dependency on UserManager<ApplicationUser>. Then, you can access the ApplicationUser through the HttpContext of the request. I wrote an extension method for my project:

     public static class IdentityExt
     {
        public static Task<T> GetCurrentUser<T>(this UserManager<T> manager, HttpContext httpContext) where T: class{
            return manager.GetUserAsync(httpContext.User);
        }
     }
    

    That returns the current user, and will allow you to access all of their properties.

    Here it is inside an action:

    public Task<IActionResult> Index(){
         var user = await _userManager.GetCurrentUser(HttpContext);
    }
    
    0 讨论(0)
提交回复
热议问题