Applicationuser in ViewComponent

560 views Asked by At

I want to get Access to the applicationUser in my viewComponent. However, this doesn´t work like a normal class that inherits from "Controller".

Does anyone know how I can access the ApplicationUser from my ViewComponent?

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

There are 1 answers

0
Sirwan Afifi On

It works like a charm. Here's your example I just tested:

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

By the way If you need to get current user, you can simply use GetUserAsync method, there's no need to using ApplicationDbContext dependency:

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