如何自定义Asp.net Identity 2用户名已经采取的验证消息?

时间:2014-12-26 10:03:28

标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity asp.net-identity-2

如何自定义Asp.net Identity 2用户名已经采用验证消息(名称XYZ已被采用。)?感谢

5 个答案:

答案 0 :(得分:21)

好吧,我没有找到任何解决这个问题的简单方法。简单来说,我的意思是在属性/模型/控制器中修改一些消息。

一种可能的解决方案可能是:

执行

var result = await UserManager.CreateAsync(user, model.Password);

如果结果不成功,您可以检查“名称XYZ已被采用”的错误属性。模式并将其替换为您的自定义消息。

另一种解决方案(这是我首选的方法)是编写自定义UserValidation类:

 /// <summary>
    ///     Validates users before they are saved to an IUserStore
    /// </summary>
    /// <typeparam name="TUser"></typeparam>
    public class CustomUserValidator<TUser> : UserValidator<TUser, string>
        where TUser : ApplicationUser
    {
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="manager"></param>
        public CustomUserValidator(UserManager<TUser, string> manager) : base(manager)
        {
            this.Manager = manager;
        }

        private UserManager<TUser, string> Manager { get; set; }

        /// <summary>
        ///     Validates a user before saving
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public override async Task<IdentityResult> ValidateAsync(TUser item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            var errors = new List<string>();
            await ValidateUserName(item, errors);
            if (RequireUniqueEmail)
            {
                await ValidateEmail(item, errors);
            }
            if (errors.Count > 0)
            {
                return IdentityResult.Failed(errors.ToArray());
            }
            return IdentityResult.Success;
        }

        private async Task ValidateUserName(TUser user, List<string> errors)
        {
            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Name"));
            }
            else if (AllowOnlyAlphanumericUserNames && !Regex.IsMatch(user.UserName, @"^[A-Za-z0-9@_\.]+$"))
            {
                // If any characters are not letters or digits, its an illegal user name
                errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.InvalidUserName, user.UserName));
            }
            else
            {
                var owner = await Manager.FindByNameAsync(user.UserName);
                if (owner != null && !EqualityComparer<string>.Default.Equals(owner.Id, user.Id))
                {
                    errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, user.UserName));
                }
            }
        }

        // make sure email is not empty, valid, and unique
        private async Task ValidateEmail(TUser user, List<string> errors)
        {
            if (!user.Email.IsNullOrWhiteSpace())
            {
                if (string.IsNullOrWhiteSpace(user.Email))
                {
                    errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Email"));
                return;
                }
                try
                {
                    var m = new MailAddress(user.Email);
                }
                catch (FormatException)
                {
                    errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.InvalidEmail, email));
                return;
                }
            }
            var owner = await Manager.FindByEmailAsync(user.Email);
            if (owner != null && !EqualityComparer<string>.Default.Equals(owner.Id, user.Id))
            {
                errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateEmail, email));
            }
        }
    }

您可以看到所有验证错误消息正在使用的资源,因此通过在资源中指定自定义格式,您将能够自定义这些消息。

您可以使用ApplicationUserManager班级Create方法注册验证码:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
   manager.UserValidator = new CustomUserValidator<ApplicationUser>(manager)
   {
       AllowOnlyAlphanumericUserNames = false,
       RequireUniqueEmail = true
   };
}

答案 1 :(得分:6)

比接受的答案容易得多。

添加一个class并从IdentityErrorDescriber继承

public class AppErrorDescriber : IdentityErrorDescriber
    {
        public override IdentityError DuplicateUserName(string userName)
        {
            var error = base.DuplicateUserName(userName);
            error.Description = "This email address has already been registered. Please log in.";
            return error;
        }
    }

现在在 Startup.cs 中使用新类即可。

services.AddDefaultIdentity<AppUser>(options => ... )
                .AddErrorDescriber<AppErrorDescriber>();

答案 2 :(得分:1)

只需按照以下方式自定义AddErrors方法:

private void AddErrors(IdentityResult result)
{
    foreach (var error in result.Errors)
    {
        if (error.StartsWith("Name"))
        {
            var NameToEmail= Regex.Replace(error,"Name","Email");
            ModelState.AddModelError("", NameToEmail);
        }
        else
        {
            ModelState.AddModelError("", error);
        }
    }
}

答案 3 :(得分:0)

使用 XLocalizer - Nuget 包进行本地化。 请参阅文档 here

答案 4 :(得分:-1)

将您自己的属性添加到ApplicationUser类的简单方法,如:

 public class AppUser:IdentityUser
  {
     public string MyUserName{get; set;}
  }