Microsoft.AspNet.Identity vnext 中的 UserValidator

2024-03-14

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

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

但是在新版本的asp.net Identity中,UserManager似乎没有一个叫UserValidator的属性。 “UserValidator”已被识别,但我想它现在以不同的方式添加到 UserManager 中。我在 UserManager 上看不到任何相关属性。

Edit:

github 存储库中“Identity”的单元测试针对这种情况进行了测试。目前它是该文件中的最后一个:

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

我想这应该给出答案的线索,但我看不出这会在我的代码中出现。

    [Theory]
    [InlineData("[email protected] /cdn-cgi/l/email-protection", 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);
        }
    }

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

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

将其更改为以下内容允许将电子邮件地址用作用户名。

// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.UserNameValidationRegex = null; })
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Microsoft.AspNet.Identity vnext 中的 UserValidator 的相关文章

随机推荐