来自UserValidator的身份c#.net核心CustomUserValidator

时间:2018-08-29 03:45:38

标签: c#

我想实现CustomUserValidator类而不是UserValidator<User>, 这样我就可以使userName不是唯一的,因为当我覆盖ValidateAsync函数并调用下面的函数时,身份拒绝重复的用户名

public class CustomUserValidator :UserValidator<User>
{
    public CustomUserValidator(): base(new IdentityErrorDescriber())
    {

    }

    public override async
    Task<IdentityResult> ValidateAsync(UserManager<User> manager, User user) {
        if (manager == null) {
            throw new ArgumentNullException(nameof(manager));
        }
        if (user == null) {
            throw new ArgumentNullException(nameof(user));
        }
        var errors = new List<IdentityError>();
        await ValidateUserName (manager, user, errors);
        if (manager.Options.User.RequireUniqueEmail) {
            await ValidateEmail (manager, user, errors);
        }
        return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success;
    }


    private async Task
    ValidateUserName(UserManager<User> manager, User user, ICollection<IdentityError> errors) {
        var userName = await manager.GetUserNameAsync(user);
        if (string.IsNullOrWhiteSpace(userName)) {
            errors.Add(Describer.InvalidUserName(userName));
        } else if (!string.IsNullOrEmpty(manager.Options.User.AllowedUserNameCharacters) &&
                userName.Any(c => !manager.Options.User.AllowedUserNameCharacters.Contains(c)))
        {
            errors.Add(Describer.InvalidUserName(userName));
        }
        else
        {
            var owner = await manager.FindByNameAsync(userName);
            if (owner != null &&
                    !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user))) {
                errors.Add(Describer.DuplicateUserName(userName));
            }
        }
    }
}

通过评论

if (owner != null && !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user))) {
    errors.Add(Describer.DuplicateUserName(userName));
}

我也收到DuplicatedUsername错误,如果我将DuplicateUserName替换为其他任何内容,也会得到此错误以及duplicatedUserName错误

有什么简单的方法可以解决吗?

0 个答案:

没有答案