Extending the UserManager
Your View shouldn't need to call back-end services on its own, you should provide it all the information it requires either through the @Model
or through ViewBag
/ViewData
/Session
.
However, if you need to get the current user you could just use:
var user = await UserManager.GetUserAsync(User);
string userName = user.Name;
If you want to have your own UserManager
, though, you'd have to do this:
public class MyManager : UserManager<ApplicationUser>
{
public MyManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{
}
public async Task<string> GetNameAsync(ClaimsPrincipal principal)
{
var user = await GetUserAsync(principal);
return user.Name;
}
}
And add it to the services:
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<SomeContext>()
.AddUserManager<MyManager>()
.AddDefaultTokenProviders();
Then you'd need to replace the references to UserManager<ApplicationUser>
for MyManager
.
Thanks to @Camilo-Terevinto I was able to figure out a solution. In my _Layout.cshtml
<span class="m-topbar__username rust-text">
@{ var u = await UserManager.GetUserAsync(User); }
@u.Name
</span>