ApplicationComponent中的Applicationuser

时间:2016-12-14 16:01:40

标签: c# asp.net-core dependency-injection asp.net-core-identity asp.net-core-viewcomponent

我想在viewComponent中访问applicationUser。但是,这不像继承自“Controller”的普通类。

有谁知道如何从我的ViewComponent访问ApplicationUser?

public class ProfileSmallViewComponent : ViewComponent
{
    private readonly ApplicationDbContext _Context;
    private readonly UserManager<ApplicationUser> _UserManager;

    public ProfileSmallViewComponent(UserManager<ApplicationUser> UserManager, ApplicationDbContext Context)
    {
        _Context = Context;
        _UserManager = UserManager;
    }

    //GET: /<controller>/
    public async Task<IViewComponentResult> InvokeAsync()
    {
        //ApplicationUser CurrentUser = _Context.Users.Where(w => w.Id == _UserManager.GetUserId(User)).FirstOrDefault();
    //Code here to get ApplicationUser

        return View("Header");
    }
}

1 个答案:

答案 0 :(得分:1)

它就像一个魅力。这是我刚刚测试过的例子:

public class ProfileSmallViewComponent : ViewComponent
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileSmallViewComponent(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var users = await _userManager.Users.ToListAsync();
        return await Task.FromResult<IViewComponentResult>(View("Header", users));
    }
}

顺便说一下如果你需要获得当前用户,你只需使用GetUserAsync方法,就不需要使用ApplicationDbContext依赖:

ApplicationUser currentUser = await _userManager.GetUserAsync(HttpContext.User);