ASP.NET MVC Identity特殊字符的电子邮件/用户名

9
当使用电子邮件“xxx-yyy@gmail.com”通过Web API注册帐户时,Fiddler返回以下错误。请注意,电子邮件也用于用户名,因此两个字段相同。但在MVC本身上注册时可以正常工作。
引用: 异常消息=用户创建失败-标识异常。错误如下: 用户名xx-yyy@gmail.com无效,只能包含字母或数字。
用户对象
 var newUser = new ApplicationUser {
            UserName = user.Email,
            Email = user.Email
        };

IdentifyConfig.cs

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

        };

我尝试注释掉AllowOnlyAlphanumericUserNames,但没有生效。正确的设置应该是将其设置为false,这样就可以允许特殊字符,比如我的情况是一个连字符(-)。 API控制器
// POST: api/auth/register
    [ActionName("Register")]
    public async Task<HttpResponseMessage> PostRegister(Auth user) {


        //dash issue is here. 

        var userContext = new ApplicationDbContext();

        var userStore = new UserStore<ApplicationUser>(userContext);

        var userManager = new UserManager<ApplicationUser>(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<HttpResponseMessage> PostRegister(Auth user) {

//Changed to the following line
            ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

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

            var result = await userManager.CreateAsync(newUser, user.PasswordHash);
2个回答

12
您正在Create方法中设置ApplicationUserManagerAllowOnlyAlphanumericUserNames = false。在您的ApiControllerPostRegister操作中,您正在新建一个ApplicationUserManager的实例。默认情况下,AllowOnlyAlphanumericUserNames为true。

您可以更改ApplicationUserManager的构造函数。

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

当您创建ApplicationUserManager的实例时,可以将AllowOnlyAlphanumericUserNames设置为false。

注意: 最好从OwinContext获取ApplicationUserManager,就像在默认MVC5模板中的AccountController中所做的那样,或者使用依赖注入。


谢谢你的解决方案!我按照你在笔记中推荐的做法进行了操作。我已经编辑了我的问题以反映出可行的解决方案。 :) - Zhi Kai

3
那是因为您所有的配置都在ApplicationUserManager中,而您在Web Api操作中没有使用它。相反,您正在创建一个普通的UserManager,然后将使用所有验证等方面的默认设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接