我想为用户名验证实现自定义逻辑。为用户名自定义验证创建了函数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
这里是数据的屏幕截图。
答案 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以使一切工作。