c# - 从部分 View 获取ApplicationUser

标签 c# asp.net-mvc asp.net-identity-2 asp.net-core-mvc

我曾问过有关旧版 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/

相关文章:

c# - 如何在 Mac 上将源代码插入 Pages 文档中?

c# - 帮助设计订单管理器类

asp.net - .Net 身份 2 与 3

c# - 为什么可以不处理 UserStore

c# - 为什么 IdentityUser 类在 Microsoft.AspNet.Identity.EntityFramework 命名空间中而不是在 Core 包中?

c# - System.NullReference Exception occurred in App_Web_XXX.dll - 局部 View 错误

c# - 带有 Microsoft Fakes 的 Stub 或 Shim Process 类

c# - 在 MVC 编辑操作 {HTTP POST} 中使用 UpdateModel 与 Request.Form 集合

javascript - 单击 html 中的链接不会将我重新路由到正确的页面

javascript - 如何将行号添加到动态添加到 html 表的行