c# - 如何在 ViewComponent Asp.Net Core 中获取当前登录用户

标签 c# asp.net-core asp.net-core-viewcomponent

我在某些页面中使用 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/

相关文章:

c# - 如何使用c#在word中插入脚注

C# - 获取列表中的倒数第二个项目

c# - 如何在一个 Controller 中使用 .net Core 创建几个 url

c# - 如何返回 HashSet 项的值而不是索引?

ajax - 我可以通过 ajax 重新加载 asp 5/MVC 6 View 组件吗?

asp.net-core - C# 使用 TagHelper 将对象传递到 ViewComponent

c# - 我的 C# 和 PHP 解密方法有何不同?

c# - 我可以在向服务添加 DbContext 之前从容器获取服务吗?

c# - 使用 Razor Pages 在 Asp.NET Core 2.2 中找不到 ViewComponent

c# - 我可以在执行存储过程之前获取行数吗?