我在某些页面中使用 ViewComponent 渲染侧边栏。我需要当前登录用户进行某些操作,如何在 ViewComponent 中获取用户?当然,我可以将 View 作为参数传递给 InvokeAsync 方法,但我正在寻找更好的方法。
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
而不是 User
在 ViewComponent 中:
public abstract class ViewComponent
{
public ClaimsPrincipal UserClaimsPrincipal { get; }
....
}
在 Controller 中:
[Controller]
public abstract class ControllerBase
{
protected ControllerBase();
public ClaimsPrincipal User { get; }
....
}
关于c# - 如何在 ViewComponent Asp.Net Core 中获取当前登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39615773/