在我的.NET Core2.0MVC项目中,我添加了额外的值来扩展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; }
}在_LoginPartial中,我想要获取名称,而不是它默认获取的UserName
@using Microsoft.AspNetCore.Identity
@using RioTintoQRManager.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
@UserManager.GetUserName(User)
}如何扩展UserManager,或者创建一个像UserManager.GetUserName一样在视图中可用的新方法?
发布于 2018-02-08 05:39:21
视图本身不需要调用后端服务,应该通过@Model或ViewBag/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();然后您需要为MyManager替换对UserManager<ApplicationUser>的引用。
发布于 2018-02-08 05:54:55
多亏了@Camilo-Terevinto,我才能找到解决方案。在我的_Layout.cshtml
<span class="m-topbar__username rust-text">
@{ var u = await UserManager.GetUserAsync(User); }
@u.Name
</span>https://stackoverflow.com/questions/48673222
复制相似问题