我想在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");
}
}
答案 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);