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?

asked Aug 26, 2016 at 20:20

1 Answer 1

4

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);
}
answered Aug 26, 2016 at 20:32
Sign up to request clarification or add additional context in comments.

2 Comments

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 :-)
@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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.