Search code examples
c#asp.net-coreasp.net-core-identity

How to add a IdentityUser IdentityResult error in ASP.Net Core for a unique email address


My "User" class inherits from "IdentityUser" and I want to make the EmailAddress unique. BUT instead of creating a unique property like this

builder.Entity<User>()
  .HasIndex(u => u.Email).IsUnique();

in the model builder that throws an exception when I try to register a duplicate email address in the method below, I'd like it to return a IdentityResult error, just like it does when I have a duplicate username. Some how Identity forgot to include a uniqueness for the email field!?

My register method where "result.Succeeded" is false if the username is taken/used and an IEnumerable of IdentityErrors, in "result.errors". I'd like to get the same type of error from a duplicate email. Is this possible?

[HttpPost("register")]
public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)
{
    var userToCreate = _mapper.Map<User>(userForRegisterDto);

    var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);

    var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);

    if (result.Succeeded)
    {
        return CreatedAtRoute("GetUser", new { controller = "Users", id = userToCreate.Id }, userToReturn);
    }

    return BadRequest(result.Errors);
}

Solution

  • This is already supported, using RequireUniqueEmail, which defaults to false. Here’s an example of how to set it to true, taken from the docs and modified accordingly:

    services.Configure<IdentityOptions>(options =>
    {
        options.User.RequireUniqueEmail = true;
    });
    

    You can achieve the same thing with the call to AddIdentity (or whichever variation you’re using). Here's an example of that approach:

    services.AddIdentity<User, Role>(options =>
    {
        options.User.RequireUniqueEmail = true;
    })