This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Now the moment you've been waiting for—testing our changes!
Preventing Duplicate Users
Our registration form currently allows users to register with an email address that's already associated with an existing account. We can update the AccountController.Register
POST action method to validate if an email address is already in use or not.
Using the ASP.NET Identity UserManager Class
Identity's UserManager class provides a wide variety of methods related to users. To determine if an existing account is associated with an email address, we can use the FindByEmail
or FindByEmailAsync
method to search for a user by their email address. If a user is returned, then we know the provided email address is in use. All we need to do then, is to add the model error.
// Validate if the provided email address is already in use.
var existingUser = await UserManager.FindByEmailAsync(viewModel.Email);
if (existingUser != null)
{
ModelState.AddModelError("Email", $"The provided email address '{viewModel.Email}' has already been used to register an account. Please sign-in using your existing account.");
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up