Search code examples
c#asp.net-coreentity-framework-coreasp.net-core-mvc

ASP.NET Core Identity InvalidUserName


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


Solution

  • Since there is a custom UserName field in APPUser, this causes a duplication with the UserName of identityUser, so an invalid error occurs. enter image description here You can add an override attribute to Appuser to avoid this error, such as:

    public class AppUser : IdentityUser<string>
    {
       
        public override string UserName { get; set; } = null!;
    }
    

    When I reinsert the data:

    public async Task<IActionResult> Register()
    {
        var user = new AppUser
        {
            Id="1",
            UserName = "johndoekk",
            Email = "[email protected]",
            FirstName = "Jonhn",
            LastName = "Dnoe",
            Name = "John Dnoe"
        };
    
        var result = await _userManager.CreateAsync(user, "123123-Aa");
    
        int sfd = 4;
    
        if (result.Succeeded)
        {
            //await SignInManager.SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
    
        return Ok();
    }
    

    enter image description here enter image description here