How to extend asp.net web api 2 user?

后端 未结 1 1872
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 17:01

I\'m building a Web API (2) project and use \"individual account\" authentication. I want to

  1. extend user with some details (lik
相关标签:
1条回答
  • 2020-12-29 17:25

    First, as in : Introduction to ASP.NET Identity

    By default, the ASP.NET Identity system stores all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.

    Now,the IdentityUser class will be mapped to AspNetUsers Table in Database,so lets extend it by create a new class that inherit from it and add our custom properties:

    public class CustomUser : IdentityUser
    {
        public string Email { get; set; }
    }
    

    Then you should let the UserManager class to use CustomUser instead of IdentityUser Class,so in Startup.cs ,change the generic type for UserManager and UserStore to be like:

    UserManagerFactory = () => new UserManager<CustomUser>(new UserStore<CustomUser>());
    

    also the property :

    public static Func<UserManager<CustomUser>> UserManagerFactory { get; set; }
    

    In ApplicationOAuthProvider.cs and any place in your solution do the same changes for generic type for UserManager,and start using CustomUser instead of IdentityUser . You can add the new "Email" property to RegisterBindingModel as :

    public class RegisterBindingModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    
        public string Email { get; set; }
    }
    

    Then in registration you can add value:

     CustomUser user = new CustomUser
            {
                UserName = model.UserName,
                Email=model.Email
            };
    

    I hope it will help

    UPDATE

    If anyone got an ExceptionMessage "Invalid column name 'Discriminator'." that means the "AspNetUsers" is already created before following my steps ,and the table doesn't have "Discriminator" column, so all what you should do is going to database,change the design of AspNetUsers table by adding a new column with type as nvarchar(128)(Also add a new column that you want to have like Email in my example),and name it Discriminator , and don't forget to fill the fields of this column for old records with the appropriate value (in my example it will be CustomUser).

    0 讨论(0)
提交回复
热议问题