Search code examples
c#asp.netasp.net-mvc-5asp.net-identity

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


Solution

  • 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()