0

我想在我的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

回答

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