Asp.net Identity不允许两个或多个用户使用相同的用户名,即使AspNetUsers表中的主键是Id,所以我试图验证UserManager的UserValidator,但它仍然给我错误,我不能给两个用户相同的用户名。这里是自定义验证器:
public class CustomUserValidator<TUser> : IIdentityValidator<TUser>
where TUser : ApplicationUser, Microsoft.AspNet.Identity.IUser
{
private readonly UserManager<TUser> _manager;
public CustomUserValidator()
{
}
public CustomUserValidator(UserManager<TUser> manager)
{
_manager = manager;
}
public async Task<IdentityResult> ValidateAsync(TUser item)
{
var errors = new List<string>();
if (_manager != null)
{
var otherAccount = await _manager.FindByNameAsync(item.UserName);
if (otherAccount != null && otherAccount.CodeClient == item.CodeClient)
errors.Add("Utilisateur existant.");
}
return errors.Any()
? IdentityResult.Failed(errors.ToArray())
: IdentityResult.Success;
}
}
在我的控制器的构造函数中,我更改uservalidator属性,如下所示:
public UsersRootController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
UserManager = userManager;
RoleManager = RoleManager;
UserManager.UserValidator = new CustomUserValidator<ApplicationUser>(userManager);
}
当我尝试调用createasync方法时:
var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, Nom = model.Nom, Prenom = model.Prenom, IsEnabled = model.IsEnabled, CodeClient = model.Client };
resultUser = await UserManager.CreateAsync(user, model.Password);
它使用我的自定义验证器,但总是返回false。
有什么办法解决这个问题吗?
我遇到了同样的问题,但使用了Role
。
问题是微软反对验证的策略!他通过IIdentityValidator
和IdentityDbContext
内部检查唯一性。为什么两次?我不知道!要解决此问题,请查看源代码(此处:https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs)就像我为Role
:做的那样简单地覆盖它
public class ApplicationIdentityDbContext : IdentityDbContext<...>
{
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
{
if (entityEntry != null && entityEntry.State == EntityState.Added)
{
//NOTE : change the following codes to support your needs!
var role = entityEntry.Entity as ApplicationRole;
if (role != null)
{
var errors = new List<DbValidationError>();
return new DbEntityValidationResult(entityEntry, errors);
}
}
return base.ValidateEntity(entityEntry, items);
}
}
之后,您应该强制Store
使用这个新上下文。