[英]How to access custom fields in ASP.Net Identity User?
我从 Asp.Net Identity 向 ApplicationUser 类添加了更多自定义字段。 我需要用户的全名、位置等字段。
现在我需要在某些视图中访问这些参数。 例如,要获取 UserName,我可以简单地使用User.Identity.GetUserName()
获取它。
如何从视图内的 ApplicationUser 类访问 FullName、Location 和其他属性?
您是否考虑过使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.