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

Using non-ASCII characters in Microsoft.AspNetCore.Identity Identity


I want set the UserName to Chinese Word, the document

services.Configure<IdentityOptions>(options =>
{
   options.User.AllowedUserNameCharacters =
   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
});

I want to set the word to Chinese word like this

var user = new IdentityUser { Email = "admin@xxx.com", UserName = "管理员" };
var result= userManager.CreateAsync(user, "admin123456"); // 等待异步方法执行完毕

the result is Id = 1, Status = RanToCompletion, Method = "{null}", Result = "Failed : InvalidUserName"


Solution

  • This is the default behaviour of ASP.NET Core Identity. You could do the following to disable validation:

    services.Configure<IdentityOptions>(options =>
    {
        options.User.AllowedUserNameCharacters = null;
    });
    

    Besides, change your code like below:

    //add await....
    var result = await _userManager.CreateAsync(user, "AD@admin123456");
    

    Note:

    The default passwords contain an uppercase character, lowercase character, a digit, and a non-alphanumeric character. Passwords must be at least six characters long.

    If you do not custom password validation, admin123456 here is not valid, you still need an uppercase character and a non-alphanumeric character.