C# ASP.NET Core – How to Fix InvalidUserName in ASP.NET Core Identity

asp.net-coreasp.net-core-mvcc++entity-framework-core

I am working on an ASP.NET Core 6 MVC application that uses ASP.NET Core Identity. When I try to create a new user using the UserManager, I get this error:

User name ' ' is invalid, can only contain letters or digits.

Username do not has any whitespace.

When I try to create new user I get the error:

var user = new User
{
    Name = "my name",
    UserName = "GoodName",
    Email = "[email protected]",
    EmailConfirmed = true
};

var result = await _userManager.CreateAsync(user, "123723-Aa");

Code in program file:

builder.Services.AddIdentity<User, Role>(options =>
{
// User settings.
    options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<School.Database.SchoolContext>()
.AddUserManager<UserManager<User>>()
.AddClaimsPrincipalFactory<ApplicationUserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();

This is repo link:

https://github.com/MrMustafa-2/TestProject.git

And when you run the project go to this url:

/Account/Register

Then you can see the error at the Breakpoint I mark it

I am waiting …

Thanks

Best Answer

References : https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.useroptions.allowedusernamecharacters?view=aspnetcore-6.0

As per the above Microsoft official documentation, AspNet_Users table's Username field default valid allowed characters are :

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+

As per your question you are using space in Username field like "any user name".

You have to use it like "any_user_name" or "anyusername" or you can just use characters from the above lists.

Still, you want to use space in your Username field, you can configure using AllowedUserNameCharacters property to modify default characters like this :

services.AddIdentity<IdentityUser<string>, IdentityRole>(options =>{
    options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/ ";
});