【问题标题】:Applicationuser in ViewComponentViewComponent 中的 Applicationuser
【发布时间】:2016-12-14 16:01:39
【问题描述】:

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

【问题讨论】:

  • "这不像从 "Controller" 继承的普通类。"。你能更明确地说为什么这个“不起作用”吗?你有例外吗?如果是这样,请将异常详细信息添加到您的问题中。

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


【解决方案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);

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多