3

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?

Community
  • 1
  • 1
Pascal
  • 12,265
  • 25
  • 103
  • 195

1 Answers1

3

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);
}
Mike_G
  • 16,237
  • 14
  • 70
  • 101
  • f..k... I tried the GetUserIdAsync before which just accepts an ApplicationUser and I could not find out how to get/cast it... Why is there no overloaded GetUserIdAsync(base.User) method ? stupid... Thanks Mike_G!!! At first I tried to get the User`s Id then I thought what about actually getting a custom property then did the question here :-) – Pascal Aug 26 '16 at 20:46
  • @Mike_G...nice extension method. I'm new to web development. What/Where is the best place in the pipeline to get the user object so its always available and only needs retrieving one time. It seems repetitious to have to ask for the user object every time you need it. – dinotom Nov 10 '17 at 11:03