【问题标题】:How to reference a custom Identity field in ASP.NET Core Web Application?如何在 ASP.NET Core Web 应用程序中引用自定义标识字段?
【发布时间】:2020-07-08 14:26:36
【问题描述】:

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

【问题讨论】:

    标签: asp.net-core asp.net-identity


    【解决方案1】:

    根据您的描述,我想您已经将 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();
        }
    

    结果如下:

    【讨论】:

    • 这正是我所需要的!非常感谢您简单直接的回答!
    猜你喜欢
    • 2019-12-16
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2019-09-14
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多