如何在ViewComponent中获取当前登录用户Asp.Net核心
问题描述:
我在某个页面中使用ViewComponent作为渲染侧边栏。我需要当前登录用户进行某些操作,如何在ViewComponent中获取用户?当然,我可以将其作为参数从视图传递到InvokeAsync方法,但我正在寻找更好的方法。如何在ViewComponent中获取当前登录用户Asp.Net核心
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();
}
}
答
在ViewComponent可以代替用户用户UserClaimsPrincipal
在ViewComponent:
public abstract class ViewComponent
{
public ClaimsPrincipal UserClaimsPrincipal { get; }
....
}
In Controller:
[Controller]
public abstract class ControllerBase
{
protected ControllerBase();
public ClaimsPrincipal User { get; }
....
}
答
答
您可以访问请求,让你可以这样说:
public async Task<IViewComponentResult> InvokeAsync()
{
_userManager.GetUserId(Request.HttpContext.User);
return View();
}