如何在Microsoft.AspNet.Identity.UserManager上设置AllowOnlyAlphanumericUserNames标志,以便UserValidator允许非字母数字用户名?
在 UserManager contructor:
UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
另一种方法:
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
// Start of new code
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
{
AllowOnlyAlphanumericUserNames = false,
};
// End of new code
}
public UserManager<ApplicationUser> UserManager { get; private set; }
}
约翰的回答是对的,我用他的回答允许电子邮件作为用户名(默认情况下不起作用)
请投票/接受约翰的回答。
这是我使用自定义用户管理器的一些代码"来使事情正常工作
(这样其他地方也减少了重复)
public class MyUserManager : UserManager<ApplicationUser>
{
public MyUserManager(DbContext db)
: base(new UserStore<ApplicationUser>(db))
{
this.UserValidator = UserValidator = new UserValidator<ApplicationUser>(this)
{ AllowOnlyAlphanumericUserNames = false };
}
}
下面是帐户控制器构造函数代码现在的样子:
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(new MyUserManager(new AppContext()))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
从 ASP.NET Identity 3.0(目前在RC中)开始,这现在配置为用户的一个选项。
public void ConfigureServices(IServiceCollection services)
{
// (Rest of code removed)
// Note the + added to the string of allowed user name characters
services.AddIdentity<ApplicationUser, IdentityRole>(o => o.User.AllowedUserNameCharacters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+")
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
与 Gist 相同的代码:https://gist.github.com/pollax/4449ce7cf47bde6b3a95
另一种方式
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
你可以像这样编写自己的UserValidator。然后使用它:
var userManager = new UserManager<ApplicationUser>(new CustomUserStore());
userManager.UserValidator = new CustomUserValidator<ApplicationUser>(userManager);