【发布时间】:2018-05-25 15:28:48
【问题描述】:
我想为用户名验证实现自定义逻辑。为用户名自定义验证创建了函数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 这是数据的屏幕截图。
【问题讨论】:
-
如果您还没有,不妨看看this question的答案
-
谢谢,我已经尝试过这个解决方案,很遗憾没有成功。
-
你找到答案了吗?
标签: asp.net-mvc validation asp.net-identity