Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the UserManager

In my .NET Core 2.0 MVC project I added additional values to extend the ApplicationUser

public class ApplicationUser : IdentityUser
    {
        public string Name { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateUpdated { get; set; }
        public DateTime LastLogin{ get; set; }

    }

In _LoginPartial I would like to get the Name, instead of the UserName which it gets by default

@using Microsoft.AspNetCore.Identity
@using RioTintoQRManager.Models

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
     @UserManager.GetUserName(User)
}

How do I extend the UserManager, or create a new method that would be available in the view like UserManager.GetUserName is?

like image 208
user6383418 Avatar asked Feb 07 '18 21:02

user6383418


2 Answers

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.

like image 110
Camilo Terevinto Avatar answered Oct 05 '22 11:10

Camilo Terevinto


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>
like image 41
user6383418 Avatar answered Oct 05 '22 09:10

user6383418