即使AspNetUsers表中的主键是Id,Asp.net Identity也不允许两个或更多用户使用相同的用户名,所以我试图使用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 .
有没有办法解决这个问题?
1 回答
我遇到了同样的问题,但是
Role
.问题是微软反对验证的策略!他通过
IIdentityValidator
以及IdentityDbContext
内部检查唯一性 . 为什么两次?我不知道!要解决这个问题,请查看源代码(这里:https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs)并简单地覆盖它,就像我为Role
做的那样:之后你应该强制你的
Store
来使用这个新的上下文 .