在我的.NET Core 2.0 MVC项目中,我添加了其他值来扩展ApplicationUser
Map<String, List<User>> groupByUser =
userList.stream().collect(Collectors.groupingBy(User::getUserName));
在_LoginPartial中我想获取名称,而不是默认获得的UserName
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public DateTime LastLogin{ get; set; }
}
如何扩展UserManager,或者创建一个在UserManager.GetUserName等视图中可用的新方法?
答案 0 :(得分:8)
您的视图不需要自行调用后端服务,您应该通过@Model
或ViewBag
/ {{1}向其提供所需的所有信息} / ViewData
。
但是,如果您需要获得当前用户,您可以使用:
Session
但是,如果你想拥有自己的var user = await UserManager.GetUserAsync(User);
string userName = user.Name;
,那么你必须这样做:
UserManager
并将其添加到服务中:
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;
}
}
然后,您需要将services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<SomeContext>()
.AddUserManager<MyManager>()
.AddDefaultTokenProviders();
的引用替换为UserManager<ApplicationUser>
。
答案 1 :(得分:2)
感谢@ Camilo-Terevinto,我找到了解决方案。在我的 _Layout.cshtml
中<span class="m-topbar__username rust-text">
@{ var u = await UserManager.GetUserAsync(User); }
@u.Name
</span>