如何自定义Asp.net身份2名已被使用验证消息? [英] How can customize Asp.net Identity 2 username already taken validation message?

查看:219
本文介绍了如何自定义Asp.net身份2名已被使用验证消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何自定义Asp.net身份2名已经采取的验证消息(名称XYZ已被使用。)?谢谢

How can i customize Asp.net Identity 2 username already taken validation message(Name XYZ is already taken.)? Thanks

推荐答案

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

Well, I didn't find any simple solution to this issue. And by simple i mean modifying some message in a attribute/model/controller.

一种可能的解决办法是:

One possible solution could be:

执行后

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

在的情况下导致不能成功,您可以检查它的错误财产名称XYZ已被使用。模式和自定义消息替换它。

In case that result is not successful you can check it's Errors property for the "Name XYZ is already taken." pattern and replace it with your custom message.

另一种解决方案(这是我的preferred方式)是写一个自定义的 UserValidation 类:

Another solution (this is my preferred way) is to write a custom UserValidation class:

 /// <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));
            }
        }
    }

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

You can see that for all the validation error messages Resources being used, So by specifying a custom format in your resources you will be able to customize those messages.

您可以注册 ApplicationUserManager 类的验证,创建方法:

You can register your validator in ApplicationUserManager class, Create method:

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

这篇关于如何自定义Asp.net身份2名已被使用验证消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆