Microsoft.AspNet.Identity vnext中的UserValidator [英] UserValidator in Microsoft.AspNet.Identity vnext
问题描述
我有一个问题,在使用microsoft.aspnet.identity时,我不能使用电子邮件地址作为用户名(创建新项目时选择的个人用户帐户-asp.net 5的默认mvc项目模板).我在很多地方都读过这是解决方案:
I have a problem where I cant use email addresses as usernames when using microsoft.aspnet.identity (Individual user accounts selected when creating new project - default mvc project template for asp.net 5). I have read in many places that this is the solution:
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
但是在新版本的asp.net身份中,UserManager似乎没有名为UserValidator的属性.可以识别"UserValidator",但是我想现在它以不同的方式添加到了UserManager中.我在UserManager上看不到任何相关属性.
But in the new version of asp.net identity, UserManager doesnt seem to have a property called UserValidator. The "UserValidator" is recognised but I suppose its added to the UserManager in a different way now. I cant see any relevant property on UserManager.
github仓库中针对"Identity"的单元测试对此情况进行了测试.当前是此文件中的最后一个:
The unit tests in the github repo for "Identity" has a test for this case. Its currently the last one in this file:
我想这应该为答案提供一个线索,但我看不到代码中的内容.
I guess this should give a clue as to the answer but I cant see where this would go in my code.
[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);
}
}
推荐答案
在Startup类的ConfigureServices方法中,AddIdentity方法具有重载,允许重配置不同的选项.
In the ConfigureServices method of the Startup class, the AddIdentity method has an overload which allows different options to be configured.
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
将其更改为以下内容,可以将电子邮件地址用作用户名.
Changing it to the below allows an email address to be used for usernames.
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.UserNameValidationRegex = null; })
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
这篇关于Microsoft.AspNet.Identity vnext中的UserValidator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!