使用相同的用户名和电子邮件创建用户总是返回无效的用户名错误

时间:2019-04-16 14:09:51

标签: c# asp.net-core-mvc asp.net-identity asp.net-core-2.0

试图使用.net core在身份表中创建用户。但是它总是返回一个错误的无效用户名。 使用以下代码创建用户

        var user = new ApplicationUser();
        user.UserName = "SuperAdmin1@gmail.com";
        user.Email = "SuperAdmin1@gmail.com";

        string userPWD = "Admin@123";

        var chkUser = await UserManager.CreateAsync(user, userPWD);

ConfigureServices如下。

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {

            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddDbContext<ApplicationDbContext>(options =>
                                                                   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@/";
        })
         .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(options =>
        {
            // Default Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

已将AllowedUserNameCharacters添加为“ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@/”

但仍然返回错误  用户名“”无效,只能包含字母或数字。

1 个答案:

答案 0 :(得分:0)

您可以在用户验证器上关闭此限制:

UserManager.UserValidator = new UserValidator<TUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }