首页 文章

Asp.net身份自定义验证

提问于
浏览
3

即使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 回答

  • 1

    我遇到了同样的问题,但是 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 来使用这个新的上下文 .

相关问题