Search code examples
c#asp.net-coreasp.net-core-viewcomponent

How get current login user in ViewComponent Asp.Net Core


I Use a ViewComponent for render sidebar in some page. I need current login User for some action, how can get User in ViewComponent? Of course I can pass as a parameter from view to InvokeAsync method, but I'm looking for a better way.

public class SideBarViewComponent : ViewComponent
{
    private readonly UserManager<User> _userManager;

    public ProfileSideBarViewComponent(UserManager<User> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
         //How access User

         _userManager.GetUserId(User);

        return View();
    }
}

Solution

  • In ViewComponent you can access to user by UserClaimsPrincipal instead of User property.

    In ViewComponent:

    public abstract class ViewComponent
    {
        public ClaimsPrincipal UserClaimsPrincipal { get; }
        ....
    }
    

    In Controller:

    [Controller]
    public abstract class ControllerBase
    {
        protected ControllerBase();
    
        public ClaimsPrincipal User { get; }
        
        ....
    }