不要使用用户名唯一的asp.net身份

时间:2018-05-24 08:30:56

标签: asp.net-mvc validation asp.net-identity

我想为用户名验证实现自定义逻辑。为用户名自定义验证创建了函数ValidateEntity,但如果我在创建用户时提供了唯一的用户名,则会点击ValidateEntity函数,如果我提供了重复的用户名,则此函数不会被命中。

IdentityModel.cs

    public class ApplicationUser : IdentityUser
        {
            public int AppId { get; set; }
            //other attributes
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                return userIdentity;
            }
        }
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
            }

            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }

            protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
            {
                if ((entityEntry != null) && (entityEntry.State == EntityState.Added))
                {
                    var user = entityEntry.Entity as ApplicationUser;
                    //custom logic for username validation
                }
                return base.ValidateEntity(entityEntry, items);
            }
        }

AccountController.cs

public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password); //shouldn't it always goto ValidateEntity function?
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            return View(model);
        }

更新 我添加了public new string UserName { get; set; },现在我收到错误Name cannot be null or empty这里是数据的屏幕截图。

enter image description here

1 个答案:

答案 0 :(得分:0)

用户名字段不是唯一的,这不是一个好习惯,除非您计划在自定义验证器中覆盖它。但是,您应该能够覆盖ApplicationUser类中的用户名字段:

public class ApplicationUser : IdentityUser
{
    public int AppId { get; set; }

    // Override username field
    public new string UserName { get; set; }

    //other attributes
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

此外,如果您的数据库已经存在,那么您还必须记住删除唯一索引UserNameIndex以使一切工作。