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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With