Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 685
Mohammad Akbari Avatar asked Nov 30 '22 16:11

Mohammad Akbari


2 Answers

In ViewComponent can user UserClaimsPrincipal instead of User

In ViewComponent:

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

In Controller:

[Controller]
public abstract class ControllerBase
{
    protected ControllerBase();

    public ClaimsPrincipal User { get; }

    ....
}
like image 70
Mohammad Akbari Avatar answered Dec 06 '22 11:12

Mohammad Akbari


you have access to the Request so you can get it like this:

public async Task<IViewComponentResult> InvokeAsync()
{
     _userManager.GetUserId(Request.HttpContext.User);

    return View();
}
like image 24
Joe Audette Avatar answered Dec 06 '22 12:12

Joe Audette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!