Pascal
Pascal

Reputation: 12885

Get property of applicationuser from the asp.net core identity

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?

Upvotes: 3

Views: 3161

Answers (1)

Mike_G
Mike_G

Reputation: 16512

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

Upvotes: 4

Related Questions