简体   繁体   中英

How to get and set custom user information in mvc 5 Identity?

My current code in as following.

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();
    }
}

I Want to add sum more properties in ApplicationUser class so that these fields available on views like

@User.Identity.FullName

My login action is placed at here

To be able to get it the way:

1 - You need to create a Claim for that user

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

2 - Once you add the claim for the user you can use this. I made this extension class so I would be able to get the claim value in the view.

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

With this you can call it like @User.Identity.FullName()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM