Extending IdentityRole and IdentityUser

前端 未结 2 1282
悲哀的现实
悲哀的现实 2021-02-09 14:33

I am using ASPNet Identity to implement security in my web application.

There is a requirements where in, I need to extend the IdentityRole and IdentityUser.

2条回答
  •  伪装坚强ぢ
    2021-02-09 15:13

    To extend User , Update your ApplicationUser class(located in IdentityModels.cs) to

    public class ApplicationUser : IdentityUser
    {
        public async Task 
            GenerateUserIdentityAsync(UserManager manager)
        {
            var userIdentity = await manager
                .CreateIdentityAsync(this, 
                    DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    
        // Use a sensible display name for views:
        [Display(Name = "Postal Code")]
        public string PostalCode { get; set; }
    
    }
    

    To Extend Role , Create a class ApplicationRole.cs

    public class ApplicationRole : IdentityRole
    {
        public ApplicationRole() : base() { }
        public ApplicationRole(string name) : base(name) { }
        public string Description { get; set; }
    }
    

    and Add the class inside IdentityConfig.cs file :

    public class ApplicationRoleManager : RoleManager
    {
        public ApplicationRoleManager(
            IRoleStore roleStore)
            : base(roleStore)
        {
        }
        public static ApplicationRoleManager Create(
            IdentityFactoryOptions options, IOwinContext context)
        {
            return new ApplicationRoleManager(
                new RoleStore(context.Get()));
        }
    }
    

    Now clear the old database, Run the application and register a user. It will create 3 more fields(Address,City,State) in AspNetUsers table and one more field(Description) into AspNetRoles table. That's it.

    For more info , go to the site : Extending Identity Role

提交回复
热议问题