Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access custom ApplicationUser property from view in ASP.net Core 2

I extended the ApplicationUser class to have 2 extra properties, FirstName and LastName. Both properties are persisted correctly in the database.

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(100)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    public string LastName { get; set; }
}

I am following a simple beginner example, and the code in question is as generated by the New Project with User Authentication command:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
            </li>
        </ul>
    </form>
}

And instead of Hello @UserManager.GetUserName(User)! I would like to say Hello ???????.FirstName!

I cannot find a way to access those extra properties from the view. Any suggestions on how to do that?

Thanks!

like image 203
H Mihail Avatar asked Nov 01 '17 12:11

H Mihail


1 Answers

You need to inject a UserManager into your service (or view in your case). This has a generic type parameter which in your case would be ApplicationUser:

UserManager<ApplicationUser> userManager;

You can then query users via the UserManager.Users property. Alternatively if you need to get the current user and have their ClaimsPrincipal you can use the following code to retrieve the corresponding ApplicationUser:

ApplicationUser user = await UserManager.GetUserAsync(claimsPrincipal);
string firstName = user.FirstName;

Although I (personally) am not so keen on it, .Net Core supports injection into views using the following syntax.

@inject UserManager<ApplicstionUser> UserManager
like image 197
SpruceMoose Avatar answered Nov 15 '22 08:11

SpruceMoose