Microsoft.AspNet.Identity vnext中的UserValidator

rda*_*ans 4 asp.net-core-mvc visual-studio-2015 asp.net-identity-3 asp.net-core

我有一个问题,当我使用microsoft.aspnet.identity(在创建新项目时选择的个人用户帐户 - asp.net 5的默认mvc项目模板)时,我无法使用电子邮件地址作为用户名.我在很多地方都读到这是解决方案:

UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
Run Code Online (Sandbox Code Playgroud)

但是在新版本的asp.net身份中,UserManager似乎没有一个名为UserValidator的属性."UserValidator"已被识别,但我想它现在以不同的方式添加到UserManager中.我无法在UserManager上看到任何相关属性.

编辑:

github repo中的单元测试"Identity"对此案例进行了测试.它目前是此文件中的最后一个:

https://github.com/aspnet/Identity/blob/dev/test/Microsoft.AspNet.Identity.Test/UserValidatorTest.cs

我想这应该给出答案的线索,但我不知道这会在我的代码中出现什么.

    [Theory]
    [InlineData("test_email@foo.com", true)]
    [InlineData("hao", true)]
    [InlineData("test123", true)]
    [InlineData("!noway", true)]
    [InlineData("foo@boz#.com", true)]
    public async Task CanAllowNonAlphaNumericUserName(string userName, bool expectSuccess)
    {
        // Setup
        var manager = MockHelpers.TestUserManager(new NoopUserStore());
        manager.Options.User.UserNameValidationRegex = null;
        var validator = new UserValidator<TestUser>();
        var user = new TestUser {UserName = userName};

        // Act
        var result = await validator.ValidateAsync(manager, user);

        // Assert
        if (expectSuccess)
        {
            IdentityResultAssert.IsSuccess(result);
        }
        else
        {
            IdentityResultAssert.IsFailure(result);
        }
    }
Run Code Online (Sandbox Code Playgroud)

rda*_*ans 5

在Startup类的ConfigureServices方法中,AddIdentity方法具有重载,允许配置不同的选项.

// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

将其更改为以下允许将电子邮件地址用于用户名.

// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.UserNameValidationRegex = null; })
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

  • 在asp核心中它不是正则表达式:services.AddIdentity <User,UserRole>(options => {options.User.AllowedUserNameCharacters ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";}) (2认同)