Get property of applicationuser from the asp.net core identity

偶尔善良 提交于 2019-12-01 05:57:41

问题


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 solution, its just a boilerplate workaround: How should I access my ApplicationUser properties from within my MVC 6 Views?

In the mvc action: base.User is not of type ApplicationUser neither is base.User.Identity. Both can not be casted into ApplicationUser.

So how can I access my custom properties put inside the applicationuser object when logged in?


回答1:


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);
}


来源:https://stackoverflow.com/questions/39174121/get-property-of-applicationuser-from-the-asp-net-core-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!