ViewComponent中的应用程序用户

问题描述:

我想在我的viewComponent中访问applicationUser。但是,这不像一个继承自“Controller”的普通类。ViewComponent中的应用程序用户

有谁知道我可以如何从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

“这doesn' t就像一个继承自“Controller”的普通类一样工作。“你能更明白为什么这个“不起作用”?你是否遇到异常?如果是这样,请将异常详细信息添加到您的问题。 – Steven

它就像一个魅力。这是你的例子,我只是测试:

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);