我曾问过有关旧版 MVC 版本和成员(member)资格的类似问题,但这些解决方案不适用于 Idendity 和 MVC 6。
我想在 _LoginPartial.cshtml 文件中显示用户的名字。因此,我想访问当前登录用户的 ApplicationUser.FirstName,而不是 "Hello "+ User.Identity.GetUserName() + "!"
。最好的方法是什么?
最佳答案
我提出了一个我认为更好的解决方案,因为它只需要每个请求搜索一次个人资料。
第一:创建用户服务
public interface IUserProfileLoader
{
Task<ApplicationUser> GetCurrentApplicationUser(ClaimsPrincipal user);
}
public class UserServices : IUserProfileLoader
{
private readonly UserManager<ApplicationUser> _userManager;
private ApplicationUser _CurrentUser;
public UserServices([FromServices]UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<ApplicationUser> GetCurrentApplicationUser(ClaimsPrincipal user)
{
if (_CurrentUser == null)
{
_CurrentUser = await _userManager.FindByIdAsync(user.GetUserId());
}
return _CurrentUser;
}
}
然后注册服务
在ConfigureServices中添加以下内容:
// Add user profile services.
services.AddScoped<IUserProfileLoader, UserServices>();
用于 View
注入(inject)服务:
@inject IUserProfileLoader UserServices
然后像这样访问属性:
@((await UserServices.GetCurrentApplicationUser(User)).Email)
用于其他地方...
您可以使用以下操作(例如)访问该服务:
[FromServices]IUserProfileLoader UserServices
我希望这会有所帮助。
关于c# - 从部分 View 获取ApplicationUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196918/