ASP.NET Identity: Error when adding duplicate usernames in AspNetUsers table
Hey everyone, I’m using ASP.NET Identity with a custom user validator to ignore duplicate username errors:
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = true;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddUserValidator<CustomValidator<ApplicationUser>>();
public class CustomValidator<TUser> : UserValidator<TUser> where TUser : class
{
public override async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
{
var result = await base.ValidateAsync(manager, user);
var errors = new List<IdentityError>();
foreach(var error in result.Errors)
{
if (error.Code != "DuplicateUserName")
{
errors.Add(error);
}
}
return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
}
}
Even with this, I’m still getting exceptions when adding users with duplicate usernames. Has anyone encountered this or know how to properly ignore duplicate usernames in Identity?
1 Reply
bro..In the Identity schema, the AspNetUsers table has a unique index on the NormalizedUserName column. So the table is has an unique index and i dont see your code changing that at all
try asking chat gpt how you can make it work, that is probably the easiest solution for your problem
if you are i ask chat gpt for you: If that “someone else” insists on duplicates, here’s the 10-second caution list you can pass along:
It’s not just a DB change — they must also replace the default IUserValidator or Identity will still block duplicates.
Logins get ambiguous if they sign in by username; they should force email-based login (keep RequireUniqueEmail = true).
Auditing, user mentions, and admin tools become trickier (you can’t identify a user by handle alone).
If you ever want a display name that can collide, the clean pattern is: keep UserName unique for auth, add DisplayName (non-unique) for the UI.
so honestly allowing duplicate username is a bad idea to start with bro