繁体   English   中英

Asp.net身份自定义验证

[英]Asp.net identity custom validation

即使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。

有没有办法解决这个问题?

我有同样的问题,但有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使用这个新的上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM