如何在mvc 5 Identity中获取和设置自定义用户信息

本文关键字:设置 自定义 用户 信息 获取 mvc Identity | 更新日期: 2023-09-27 18:14:56

我当前的代码如下:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我想在ApplicationUser类中添加更多属性,以便这些字段在视图上可用,如

@User.Identity.FullName

我的登录操作放在这里

如何在mvc 5 Identity中获取和设置自定义用户信息

能够得到它的方式:

1 -您需要为该用户创建一个Claim

HttpContext.Current.GetOwinContext().GetUserManager<UserManager>().AddClaimsAsync(UserId, new Claim("FullName", "The value for the full name"));

2 -一旦你为用户添加了声明,你就可以使用它了。我创建了这个扩展类,这样我就可以在视图中获取索赔值。

public static class IdentityExtensions
{
    public static string FullName(this IIdentity identity)
    {
        return ((ClaimsIdentity)identity).FindFirst("FullName")?.Value;
    }
}

你可以把它命名为@User.Identity.FullName()