【问题标题】:How to access custom fields in ASP.Net Identity User?如何访问 ASP.Net 身份用户中的自定义字段?
【发布时间】:2019-08-28 00:20:05
【问题描述】:

我在 Asp.Net Identity 的 ApplicationUser 类中添加了更多自定义字段。我需要用户的全名、位置等字段。

现在我需要在某些视图中访问这些参数。 例如,要获取用户名,我可以简单地使用User.Identity.GetUserName() 获取它。

如何从视图中的 ApplicationUser 类访问 FullName、Location 和其他属性?

【问题讨论】:

  • 到目前为止你尝试过做什么?
  • 我试过在我的视图中添加这个,但我失败了。 var user = await _userManager.FindByEmailAsync(User.Identity.Name);
  • 你能发布你的代码吗?
  • var user = await _userManager.FindByEmailAsync(User.Identity.Name);您不应该输入电子邮件而不是名称吗?

标签: c# asp.net identity


【解决方案1】:

您考虑过使用Claim 吗?用户登录时,Claim 会自动加载到 Context Identity。

在创建用户时添加声明

await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));

创建身份扩展

namespace MyApps.Extension
{
    public static class IdentityExtension
    {
        public static string GetFullName(this IIdentity identity)
        {
            if (identity == null)
                return null;

            var fullName = (identity as ClaimsIdentity).FirstOrNull("FullName");

            return fullName;
        }


        internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
        {
            var val = identity.FindFirst(claimType);

            return val == null ? null : val.Value;
        }
    }
}

以后使用

httpContextAccessor.HttpContext.User.Identity.GetFullName()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2019-04-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多