Get property of applicationuser from the asp.net core identity

前端 未结 1 1384
遥遥无期
遥遥无期 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. 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 GetCurrentUser(this UserManager 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 Index(){
         var user = await _userManager.GetCurrentUser(HttpContext);
    }
    

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题