0
votes

I have an asp.net MVC project with authentication. The default implementation uses email address for either registering users or logging them in, but in my project I don't need their email address and I want to use simple string username, therefore I have included the following code in my OnModelCreating method to exclude email addresses and some other features that I don't need:

modelBuilder.Entity<ApplicationUser>().Ignore(p => p.AccessFailedCount).
            Ignore(p => p.Email).Ignore(p => p.EmailConfirmed).Ignore(p => p.LockoutEnabled).
            Ignore(p => p.LockoutEndDateUtc).Ignore(p => p.PhoneNumber).
            Ignore(p => p.PhoneNumberConfirmed).Ignore(p => p.TwoFactorEnabled);

I have changed the LoginViewModel and Login.cshtml and replaced email address fields with username, but when I try to login an exception is raised in Login action in the following line:

var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, 
            model.RememberMe, shouldLockout: false);

The error page says:

The property 'Email' is not a declared property on type 'ApplicationUser'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.

The question is how can I completely exclude email?

1

1 Answers

0
votes

You don't need to make changes in the OnModelCreating method. All you need to do is make a few changes in the ViewModel and the Login & Register method.

  1. Replace the Email property name with the Username and comment out the [EmailAddress] annotation.
  2. Replace the Email property with Username in the Login view.
  3. In the Login method replace the model.Email with model.Username. You will notice that the Identity uses the PasswordSignInAsync method which takes the username as the parameter.

Similarly, you have to add the Username field for the RegisterViewModel, Register method, and the view to allow the user to enter the Username at the time of registration.

You don't need to explicitly ignore the Email field in the OnModelCreating method.