Invalid UserName in ASP.NET Core 6

mostafa ahmed 41 Reputation points
2024-07-22T09:02:47.1366667+00:00

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 whitespaces.

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

var user = new User
 {
     UserName = "SpecialName",
     Email = "example@domain.com"
 };

 var result = await _userManager.CreateAsync(user, "pAssR!43");

The Code in program file:

builder.Services.AddIdentity<User, Role>(options =>
{
     options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
     options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<School.Database.SchoolContext>()
.AddUserManager<UserManager<User>>()
.AddClaimsPrincipalFactory<ApplicationUserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
749 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,598 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,997 questions
{count} votes

Accepted answer
  1. Jalpa Panchal-MSFT 555 Reputation points Microsoft Vendor
    2024-07-23T06:53:35.7733333+00:00

    As the Asp.net Identity has its own username property so you could try to override by using the below code:

    Modelx.cs:

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Options;
    using System.Resources;
    namespace School.Web.Help
    {
        public class AppUser : IdentityUser<string>
        {
            public string Id { get; set; } = null!;
            public string? Email { get; set; }
            public bool EmailConfirmed { get; set; }
            public string? PasswordHash { get; set; }
            public string? SecurityStamp { get; set; }
            public string? PhoneNumber { get; set; }
            public bool PhoneNumberConfirmed { get; set; }
            public bool TwoFactorEnabled { get; set; }
            public DateTime? LockoutEndDateUtc { get; set; }
            public bool LockoutEnabled { get; set; }
            public int AccessFailedCount { get; set; }
            public override string UserName { get; set; } = null!;
            public string? Name { get; set; }
            public string? NormalizedUserName { get; set; }
            public string? NormalizedEmail { get; set; }
            public string? ConcurrencyStamp { get; set; }
            public DateTimeOffset? LockoutEnd { get; set; }
            public string? FirstName { get; set; }
            public string? LastName { get; set; }
        }
        
        public class AppRole : IdentityRole<string>
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }
        public class AppRoleClaim : IdentityRoleClaim<string>
        {
            public int Id { get; set; }
            public string RoleId { get; set; } = null!;
            public string? ClaimType { get; set; }
            public string? ClaimValue { get; set; }
        }
        public class AppUserClaim : IdentityUserClaim<string>
        {
            public string Id { get; set; }
            public string UserId { get; set; } = null!;
            public string? ClaimType { get; set; }
            public string? ClaimValue { get; set; }
        }
        public class AppUserLogin : IdentityUserLogin<string>
        {
            public string LoginProvider { get; set; }
            public string ProviderKey { get; set; }
            public string UserId { get; set; }
        }
        public class AppUserRole : IdentityUserRole<string>
        {
            public string Id { get; set; }
            public string RoleId { get; set; }
        }
        public class AppUserToken : IdentityUserToken<string>
        {
            public string UserId { get; set; } = null!;
            public string LoginProvider { get; set; } = null!;
            public string Name { get; set; } = null!;
            public string? Value { get; set; }
        }
        public sealed class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<AppUser, AppRole>
        {
            public ApplicationUserClaimsPrincipalFactory(UserManager<AppUser> userManager, RoleManager<AppRole> roleManager, IOptions<IdentityOptions> options) : base(userManager, roleManager, options)
            {
            }
        }
    }
    

    AccountController.cs:

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.AspNetCore.Identity.UI.Services;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.WebUtilities;
    using School.ViewModel;
    using System.Text.Encodings.Web;
    using System.Text;
    using School.Web.Help;
    // /Account/Register
    namespace School.Web.Controllers
    {
        public class AccountController : Controller
        {
            private SignInManager<AppUser> _signInManager;
            private UserManager<AppUser> _userManager;
            private readonly IHttpContextAccessor _accessor;
            public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, IHttpContextAccessor accessor)
            {
                _userManager = userManager;
                _signInManager = signInManager;
                _accessor = accessor;
            }
            [AllowAnonymous]
            public async Task<IActionResult> Register()
            {
                var user = new AppUser
                {
                    Id = "111",
                    UserName = "qwerty",
                    Email = "test@gmail.com",
                    EmailConfirmed = true
                };
                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 View();
            }
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Register(RegisterVM model)
            {
                if (ModelState.IsValid)
                {
                    var user = new AppUser
                    {
                        
                        UserName = model.Email,
                        Email = model.Email,
                        EmailConfirmed = true
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                // If we got this far, something failed, redisplay form
                return View(model);
            }
            private IdentityUser CreateUser()
            {
                try
                {
                    return Activator.CreateInstance<IdentityUser>();
                }
                catch
                {
                    throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " +
                        $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
                        $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
                }
            }
            [AllowAnonymous]
            public ActionResult Login(string returnUrl)
            {
                return View();
            }
            //
            // POST: /Account/Login
            [ValidateAntiForgeryToken]
            [HttpPost]
            [AllowAnonymous]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                    // This doesn't count login failures towards account lockout
                    // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                    var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return View(model);
                    }
                }
                return View(model);
            }
            //
            // POST: /Account/LogOff
            //[HttpPost]
            //[ValidateAntiForgeryToken]
            public ActionResult LogOff()
            {
                //SignInManager.SignOutAsync();
                return RedirectToAction("Index", "Home");
            }
        }
    }
    
    
    

    User's image

    Best regards,

    Jalpa


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.