如何访问 ASP.Net Identity User 中的自定义字段?
How to access custom fields in ASP.Net Identity User?
我已经从 Asp.Net 身份向 ApplicationUser class 添加了更多自定义字段。我需要用户全名、位置等字段
现在我需要在某些视图中访问这些参数。
例如,要获取用户名,我可以简单地使用 User.Identity.GetUserName()
获取它。
如何从视图中的 ApplicationUser class 访问 FullName、Location 和其他属性?
您考虑过使用 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()
我已经从 Asp.Net 身份向 ApplicationUser class 添加了更多自定义字段。我需要用户全名、位置等字段
现在我需要在某些视图中访问这些参数。
例如,要获取用户名,我可以简单地使用 User.Identity.GetUserName()
获取它。
如何从视图中的 ApplicationUser class 访问 FullName、Location 和其他属性?
您考虑过使用 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()