AspNet Identity 2.0 Email and UserName duplication

后端 未结 2 431
情深已故
情深已故 2021-01-05 10:41

My current Asp.Net MVC 5 project mandates Email address for UserName. Now I want to upgrade ASPNet Identity v1.0 to v2.0 to leverage all

相关标签:
2条回答
  • 2021-01-05 11:14

    You can try one of these:

    1. Try to ignore it by either overriding Email property in your User class and unmapping it or using fluent API.

      public class ApplicationUser : IdentityUser
      {
        // ....
      
        [NotMapped]
        public override string Email { get; set; }
      }
      

      or

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Entity<ApplicationUser>().Ignore(u => u.Email);
      }
      
    2. When you register your user just make sure that you populate Email with your UserName

      public async Task<ActionResult> Register(RegisterViewModel model)
      {
          if (ModelState.IsValid)
          {
              var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
              // ...
          }
      }
      

    Of course, you can always ignore Email column if you're not going to use it, since it allows NULLs, it'll just be sitting in your AspNetUsers table with bunch of NULLs, not the best approach but remember that by ignoring it you might lose new features that ASP.NET Identity 2 might offer that you might want to use.

    NOTE However I'm not sure if option number 1 will work on Email property since it's probably used all over the place in new Identity code. Worth a try though. I know that's how you can get rid of other columns if you don't need them. I personally happen to use new Email property/column so I haven't tried it.

    Not sure if it helps you, but thought I'd share it just in case.

    0 讨论(0)
  • 2021-01-05 11:26

    I have the same problem, and the way that I resolved it was that the email address was the same as the username when creating a user:

    var newUser = new ApplicationUser()
    {
        UserName = email,
        Email = email,
    };
    

    However, if you try to create an account with a duplicate username, you will get 2 validation errors, one for the username field, and one for the email address.

    To get around that, allow email addresses to not be unique (they will still be unique though as your usernames are unique) by editing the identityconfig.cs file:

    manager.UserValidator = new UserValidator<ApplicationUser>(manager)
                {
                    AllowOnlyAlphanumericUserNames = false,
                    RequireUniqueEmail = false
                };
    
    0 讨论(0)
提交回复
热议问题