具有特殊字符的ASP.NET MVC标识电子邮件/用户名

通过Web API使用“xxx-yyy@gmail.com”等电子邮件注册帐户时,Fiddler会返回以下错误。 请注意,电子邮件也用于用户名,因此两个字段都相同 。 但它在注册MVC本身时有效。

ExceptionMessage =用户创建失败 – 身份exception。 错误是:

用户名xx-yyy@gmail.com无效,只能包含字母或数字。

用户对象

var newUser = new ApplicationUser { UserName = user.Email, Email = user.Email }; 

IdentifyConfig.cs

 public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore(context.Get())); // Configure validation logic for usernames manager.UserValidator = new UserValidator(manager) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = false }; 

我试过注释掉AllowOnlyAlphanumericUserNames,但它没有用。 通过将其设置为false应该允许特殊字符,在我的例子中是连字符( – )。

API控制器

 // POST: api/auth/register [ActionName("Register")] public async Task PostRegister(Auth user) { //dash issue is here. var userContext = new ApplicationDbContext(); var userStore = new UserStore(userContext); var userManager = new UserManager(userStore); var newUser = new ApplicationUser { UserName = user.Email, Email = user.Email }; var result = await userManager.CreateAsync(newUser, user.PasswordHash); if (result.Succeeded) { ... 

IdentityConfig.cs没有任何变化。 仅对我的API控制器进行了更改。

  // POST: api/auth/register [ActionName("Register")] public async Task PostRegister(Auth user) { //Changed to the following line ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager(); var newUser = new ApplicationUser { UserName = user.Email, Email = user.Email }; var result = await userManager.CreateAsync(newUser, user.PasswordHash); 

您正在ApplicationUserManager Create方法中设置AllowOnlyAlphanumericUserNames = false 。 在PostRegister操作中,您正在创建ApplicationUserManager的实例。 默认情况下, AllowOnlyAlphanumericUserNames为true。

您可以更改ApplicationUserManager的构造函数

 public ApplicationUserManager(IUserStore store): base(store) { UserValidator = new UserValidator(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; } 

这样,当您新建ApplicationUserManger实例时, AllowOnlyAlphanumericUserNames将设置为false。

注意:OwinContext获取ApplicationUserManager与在默认MVC5模板的AccountController中完成相同或使用dependency injection更好。

那是因为您的所有配置都在ApplicationUserManager ,您在Web Api操作中没有使用它。 相反,您正在创建普通的UserManager ,然后将使用默认值进行所有validation等。