如何在 ASP.NET 核心 Web 应用程序中引用自定义身份字段?

How to reference a custom Identity field in ASP.NET Core Web Application?

在我的 ASP.NET 核心 Web 应用程序中,我使用 ApplicationUser 模型在我的身份中添加了自定义字段,例如 CompanyCode。我现在正在尝试检索 Web 应用程序中当前登录用户的 CompanyCode,但我不知道如何访问该字段。如何做到这一点?

根据您的描述,我想您已经将 CompanyCode 添加到 ApplicationUser 模型,并将服务和 UserManager 配置为使用 ApplicationUser 模型。像这样:

用户管理器:

    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

Setup.cs 配置服务:

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

那么,您可以尝试使用以下代码访问 CompanyCode 字段:

@UserManager.GetUserAsync(User).Result.CompanyCode

例如:

在 _LoginPartial.cshtml 页面中:

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name! @UserManager.GetUserAsync(User).Result.CompanyCode</a>
</li>

登录后结果如下:

或者,在控制器动作方法中:

    private readonly ILogger<HomeController> _logger; 
    private readonly UserManager<ApplicationUser> _userManager;
    public HomeController(ILogger<HomeController> logger,  UserManager<ApplicationUser> usermanager)
    {
        _logger = logger; 
        _userManager = usermanager;
    }

    public IActionResult Index()
    { 
        if (this.User.Identity.IsAuthenticated)
        { 
            //login success
            var item = _userManager.GetUserAsync(this.User).Result.CompanyCode;
        }
        return View();
    }

结果是这样的: