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。
有没有办法解决这个问题?