如何本地化ASP.NET身份用户名和密码错误消息?
是否有可能为“系统”ASP.NET Identity v1错误消息提供本地化的string,如“ 名称XYZ已被占用 ”或“ 用户名称XYZ无效,只能包含字母或数字 ”?
还没有,我们有一个跟踪这个工作项目的错误,以便指定资源的来源。
截至2014年3月20日发布的第2版身份,您现在可以拥有本地化的错误消息。
首先安装身份本地化软件包。
Install-Package Microsoft.AspNet.Identity.Core.fr
然后,必须设置适当的文化,以获得本地化的消息,例如设置文化的一种方式是在web.config中
<system.web> <globalization culture="fr-FR" uiCulture="fr"/> </system.web>
对于ASP.NET Core:(Microsoft.AspNetCore.Identity 1.0.0)
创build一个inheritanceIdentityErrorDescriber的类并覆盖所需的错误消息。
public class CustomIdentityErrorDescriber : IdentityErrorDescriber { public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = $"An unknown failure has occurred." }; } public override IdentityError ConcurrencyFailure() { return new IdentityError { Code = nameof(ConcurrencyFailure), Description = "Optimistic concurrency failure, object has been modified." }; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = "Incorrect password." }; } public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(InvalidToken), Description = "Invalid token." }; } public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = "A user with this login already exists." }; } public override IdentityError InvalidUserName(string userName) { return new IdentityError { Code = nameof(InvalidUserName), Description = $"User name '{userName}' is invalid, can only contain letters or digits." }; } public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(InvalidEmail), Description = $"Email '{email}' is invalid." }; } public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = $"User Name '{userName}' is already taken." }; } public override IdentityError DuplicateEmail(string email) { return new IdentityError { Code = nameof(DuplicateEmail), Description = $"Email '{email}' is already taken." }; } public override IdentityError InvalidRoleName(string role) { return new IdentityError { Code = nameof(InvalidRoleName), Description = $"Role name '{role}' is invalid." }; } public override IdentityError DuplicateRoleName(string role) { return new IdentityError { Code = nameof(DuplicateRoleName), Description = $"Role name '{role}' is already taken." }; } public override IdentityError UserAlreadyHasPassword() { return new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = "User already has a password set." }; } public override IdentityError UserLockoutNotEnabled() { return new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = "Lockout is not enabled for this user." }; } public override IdentityError UserAlreadyInRole(string role) { return new IdentityError { Code = nameof(UserAlreadyInRole), Description = $"User already in role '{role}'." }; } public override IdentityError UserNotInRole(string role) { return new IdentityError { Code = nameof(UserNotInRole), Description = $"User is not in role '{role}'." }; } public override IdentityError PasswordTooShort(int length) { return new IdentityError { Code = nameof(PasswordTooShort), Description = $"Passwords must be at least {length} characters." }; } public override IdentityError PasswordRequiresNonAlphanumeric() { return new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = "Passwords must have at least one non alphanumeric character." }; } public override IdentityError PasswordRequiresDigit() { return new IdentityError { Code = nameof(PasswordRequiresDigit), Description = "Passwords must have at least one digit ('0'-'9')." }; } public override IdentityError PasswordRequiresLower() { return new IdentityError { Code = nameof(PasswordRequiresLower), Description = "Passwords must have at least one lowercase ('a'-'z')." }; } public override IdentityError PasswordRequiresUpper() { return new IdentityError { Code = nameof(PasswordRequiresUpper), Description = "Passwords must have at least one uppercase ('A'-'Z')." }; } }
在您的Startup类上,在ConfigureServices中注册自定义ErrorDesigned:
services.AddIdentity<ApplicationUser, IdentityRole>() .AddErrorDescriber<CustomIdentityErrorDescriber>(); // Add this line
更新:下面你可以find西class牙语和葡萄牙语已经翻译的版本。 仔细检查他们!
public class SpanishIdentityErrorDescriber : IdentityErrorDescriber { public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = $"Ha ocurrido un error." }; } public override IdentityError ConcurrencyFailure() { return new IdentityError { Code = nameof(ConcurrencyFailure), Description = "Ha ocurrido un error, el objeto ya ha sido modificado (Optimistic concurrency failure)." }; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = "Password Incorrecta." }; } public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(InvalidToken), Description = "Ha ingresado un código Inválido." }; } public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = "Un usuario con ese nombre ya existe." }; } public override IdentityError InvalidUserName(string userName) { return new IdentityError { Code = nameof(InvalidUserName), Description = $"El nombre de usuario '{userName}' es inválido. Solo puede contener letras y números." }; } public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(InvalidEmail), Description = $"La dirección de email '{email}' es incorrecta." }; } public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = $"El usuario '{userName}' ya existe, por favor ingrese un nombre diferente." }; } public override IdentityError DuplicateEmail(string email) { return new IdentityError { Code = nameof(DuplicateEmail), Description = $"La direccion de email '{email}' ya se encuentra registrada. Puede recupar su contraseña para ingresar nuevamente al sistema." }; } public override IdentityError InvalidRoleName(string role) { return new IdentityError { Code = nameof(InvalidRoleName), Description = $"El nombre de rol '{role}' es inválido." }; } public override IdentityError DuplicateRoleName(string role) { return new IdentityError { Code = nameof(DuplicateRoleName), Description = $"El nombre de rol '{role}' ya existe." }; } public override IdentityError UserAlreadyHasPassword() { return new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = "El usuario ya tiene contraseña." }; } public override IdentityError UserLockoutNotEnabled() { return new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = "El bloqueo no esta habilitado para este usuario." }; } public override IdentityError UserAlreadyInRole(string role) { return new IdentityError { Code = nameof(UserAlreadyInRole), Description = $"El usuario ya es parte del rol '{role}'." }; } public override IdentityError UserNotInRole(string role) { return new IdentityError { Code = nameof(UserNotInRole), Description = $"El usuario no es parte del rol '{role}'." }; } public override IdentityError PasswordTooShort(int length) { return new IdentityError { Code = nameof(PasswordTooShort), Description = $"La contraseña deben tener un largo mínimo de {length} caracteres." }; } public override IdentityError PasswordRequiresNonAlphanumeric() { return new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = "La contraseña debe contener al menos un caracter alfanumérico." }; } public override IdentityError PasswordRequiresDigit() { return new IdentityError { Code = nameof(PasswordRequiresDigit), Description = "La contraseña debe incluir al menos un dígito ('0'-'9')." }; } public override IdentityError PasswordRequiresLower() { return new IdentityError { Code = nameof(PasswordRequiresLower), Description = "La contraseña debe incluir al menos una letra minúscula ('a'-'z')." }; } public override IdentityError PasswordRequiresUpper() { return new IdentityError { Code = nameof(PasswordRequiresUpper), Description = "La contraseña debe incluir al menos una letra MAYÚSCULA ('A'-'Z')." }; } }
葡萄牙语:(非常感谢furlanrapha )
public class PortugueseIdentityErrorDescriber : IdentityErrorDescriber { public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = $"Um erro desconhecido ocorreu." }; } public override IdentityError ConcurrencyFailure() { return new IdentityError { Code = nameof(ConcurrencyFailure), Description = "Falha de concorrência otimista, o objeto foi modificado." }; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = "Senha incorreta." }; } public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(InvalidToken), Description = "Token inválido." }; } public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = "Já existe um usuário com este login." }; } public override IdentityError InvalidUserName(string userName) { return new IdentityError { Code = nameof(InvalidUserName), Description = $"Login '{userName}' é inválido, pode conter apenas letras ou dígitos." }; } public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(InvalidEmail), Description = $"Email '{email}' é inválido." }; } public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = $"Login '{userName}' já está sendo utilizado." }; } public override IdentityError DuplicateEmail(string email) { return new IdentityError { Code = nameof(DuplicateEmail), Description = $"Email '{email}' já está sendo utilizado." }; } public override IdentityError InvalidRoleName(string role) { return new IdentityError { Code = nameof(InvalidRoleName), Description = $"A permissão '{role}' é inválida." }; } public override IdentityError DuplicateRoleName(string role) { return new IdentityError { Code = nameof(DuplicateRoleName), Description = $"A permissão '{role}' já está sendo utilizada." }; } public override IdentityError UserAlreadyHasPassword() { return new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = "Usuário já possui uma senha definida." }; } public override IdentityError UserLockoutNotEnabled() { return new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = "Lockout não está habilitado para este usuário." }; } public override IdentityError UserAlreadyInRole(string role) { return new IdentityError { Code = nameof(UserAlreadyInRole), Description = $"Usuário já possui a permissão '{role}'." }; } public override IdentityError UserNotInRole(string role) { return new IdentityError { Code = nameof(UserNotInRole), Description = $"Usuário não tem a permissão '{role}'." }; } public override IdentityError PasswordTooShort(int length) { return new IdentityError { Code = nameof(PasswordTooShort), Description = $"Senhas devem conter ao menos {length} caracteres." }; } public override IdentityError PasswordRequiresNonAlphanumeric() { return new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = "Senhas devem conter ao menos um caracter não alfanumérico." }; } public override IdentityError PasswordRequiresDigit() { return new IdentityError { Code = nameof(PasswordRequiresDigit), Description = "Senhas devem conter ao menos um digito ('0'-'9')." }; } public override IdentityError PasswordRequiresLower() { return new IdentityError { Code = nameof(PasswordRequiresLower), Description = "Senhas devem conter ao menos um caracter em caixa baixa ('a'-'z')." }; } public override IdentityError PasswordRequiresUpper() { return new IdentityError { Code = nameof(PasswordRequiresUpper), Description = "Senhas devem conter ao menos um caracter em caixa alta ('A'-'Z')." }; } }
我遇到了同样的问题,发现一个快速和肮脏的解决方法。 我查看了使用DotPeek的Microsoft.AspNet.Identity.Core
程序集(我假设任何C#反编译程序都会这样做),并且发现了两个负责这样的消息的类:
-
Microsoft.AspNet.Identity.UserValidator<TUser>
(与用户名有关) -
Microsoft.AspNet.Identity.MinimumLengthValidator
(与密码相关)
这些类不包含任何外部引用(除了要replace的string资源之外),因此在自己的代码中重新实现它们应该相当简单。
这样做后,不要忘记在你的UserManager
正确使用它们:
UserManager.UserValidator = new MyCustomUserValidator<MyUserType>(UserManager); UserManager.PasswordValidator = new MyCustomMinimumLengthValidator(6);
ASP NET Core解决方法(25.11.2016)
您可以将IStringLocalizer注入到自定义IdentityErrorDescriber中
1)创build自定义IdentityErrorDescriber(请参阅Gerardo Grignoli的答案)
public class MultilanguageIdentityErrorDescriber : IdentityErrorDescriber { private readonly IStringLocalizer<SharedResource> _localizer; public MultilanguageIdentityErrorDescriber(IStringLocalizer<SharedResource> localizer) { _localizer = localizer; } public override IdentityError DuplicateEmail(string email) { return new IdentityError() { Code = nameof(DuplicateEmail), Description = string.Format(_localizer["Email {0} is already taken."], email) }; } // DuplicateUserName, InvalidEmail, DuplicateUserName etc }
2)在Startup.cs中注册MultilanguageIdentityErrorDescriber
services.AddIdentity<IdentityUser, IdentityRole>() .AddErrorDescriber<MultilanguageIdentityErrorDescriber>() .AddDefaultTokenProviders();
3)将错误消息添加到SharedResource.language.resx。
1AmirJalali的方法完美。 虽然在web.config中设置文化的工作,如果需要也可以dynamic设置,这是如何实现的:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
在上面的代码示例中,cultureName是要设置的文化的名称。 可以在“备注”标题下find文化列表: http : //msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx
希望这可以帮助。
这个问题已经困扰了我很长一段时间了,所以我试图想出一些通用的,因为解决scheme与特定的文化安装Identity.Core只工作,如果包是可用的所有:)
以下是我如何实现适当的本地化的步骤:
- 看着在
ApplicationUserManager
默认使用的使用dotPeak的Microsoft.AspNet.Identity.PasswordValidator
的实现, - 然后,我想出了我自己实现的
class CustomPasswordValidator : PasswordValidator
并覆盖ValidateAsync
方法不返回带有错误消息的IdentityResult
,而是与这些错误消息的“代码”,所有这些错误消息前缀“CustomValidator”string。 - 然后在
AccountController
我更改了从Register
邮件中调用的AddErrors
,以便根据错误代码从我自己的资源文件中提供本地化的错误消息。
这里是CustomPasswordValidator
和实用程序类PasswordValidatorCodes
包含错误代码和方法来检索基于这些代码本地化的错误消息(AccountStrings是一个资源文件):
public static class PasswordValidatorCodes { public const string ErrorCodePrefix = "CustomPassword"; public const string PasswordTooShort = ErrorCodePrefix + "TooShort"; public const string PasswordRequireNonLetterOrDigit = ErrorCodePrefix + "RequireNonLetterOrDigit"; public const string PasswordRequireDigit = ErrorCodePrefix + "RequireDigit"; public const string PasswordRequireLower = ErrorCodePrefix + "RequireLower"; public const string PasswordRequireUpper = ErrorCodePrefix + "RequireUpper"; public static string GetLocalizedMessageForCode(string code) { switch (code) { case PasswordTooShort: return string.Format(AccountStrings.ValidationPasswordTooShort, CustomPasswordValidator.RequiredPasswordLength); case PasswordRequireNonLetterOrDigit: return AccountStrings.ValidationPasswordRequireNonLetterOrDigit; case PasswordRequireDigit: return AccountStrings.ValidationPasswordRequireDigit; case PasswordRequireLower: return AccountStrings.ValidationPasswordRequireLower; case PasswordRequireUpper: return AccountStrings.ValidationPasswordRequireUpper; default: throw new ArgumentException("code"); } } } public class CustomPasswordValidator : PasswordValidator { public const int RequiredPasswordLength = 6; public CustomPasswordValidator() { RequiredLength = RequiredPasswordLength; RequireNonLetterOrDigit = false; RequireDigit = true; RequireLowercase = true; RequireUppercase = false; } public override Task<IdentityResult> ValidateAsync(string item) { if (item == null) throw new ArgumentNullException("item"); var list = new List<string>(); if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength) { list.Add(PasswordValidatorCodes.PasswordTooShort); } if (RequireNonLetterOrDigit && item.All(IsLetterOrDigit)) { list.Add(PasswordValidatorCodes.PasswordRequireNonLetterOrDigit); } if (RequireDigit && item.All(c => !IsDigit(c))) { list.Add(PasswordValidatorCodes.PasswordRequireDigit); } if (RequireLowercase && item.All(c => !IsLower(c))) { list.Add(PasswordValidatorCodes.PasswordRequireLower); } if (RequireUppercase && item.All(c => !IsUpper(c))) { list.Add(PasswordValidatorCodes.PasswordRequireUpper); } return Task.FromResult(list.Count == 0 ? IdentityResult.Success : new IdentityResult(list)); } }
这里是修改后的AccountController.AddErrors
方法。 正如你可以看到我添加一个错误的属性Password
的模型,因为如果Password
没有通过validation,那么我想错误消息显示的Password
字段,而不是在validation总结。 这是我的CustomPasswordValidator
直接生成错误代码而不是错误消息的唯一原因:
private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { if (error.StartsWith(PasswordValidatorCodes.ErrorCodePrefix)) { ModelState.AddModelError("Password", PasswordValidatorCodes.GetLocalizedMessageForCode(error)); continue; } ModelState.AddModelError(string.Empty, error); } }
最后但并非最不重要的,不要忘记修改IdentityConfig
文件,即:
manager.PasswordValidator = new CustomPasswordValidator();
更新:
直到现在,我注意到Marselus Chia(见其他答案)已经提出了类似的解决scheme,但为VB。
让我和你分享我用西class牙语来完成这件事情。 在那里你可以轻松地自定义消息!
string Errores = result.Errors.FirstOrDefault(); Errores = Errores.Replace("Name " + Email.Text + " is already taken.", "- El mail " + Email.Text + " ya fue registrado. Intente recuperar la clave.<br/>"); Errores = Errores.Replace("Passwords must be at least 6 characters.", "- La clave debe contener por lo menos 6 caracteres.<br/>"); Errores = Errores.Replace("Passwords must have at least one non letter or digit character.", "- La clave debe contener por lo menos un caracter que no sea letra ni dígito. Por ejemplo: un punto.<br/>"); Errores = Errores.Replace("Passwords must have at least one digit ('0'-'9').", "- La clave debe contener al menos un dígito (entre 0 y 9).<br/>"); Errores = Errores.Replace("Passwords must have at least one uppercase ('A'-'Z').", "- La clave debe contener al menos una letra (entre A y Z).<br/>"); ErrorMessage.Text = "Errores:<br/><br/>" + Errores;
我的解决scheme是从Microsoft.AspNet.Identity.PasswordValidator创build新的自定义密码validation类inheritance,覆盖发出错误消息的ValidateAsync。 自定义错误信息在这里,它适用于我…
这些类假设你有一个全局资源文件名validation器。 这些类和资源文件示例中的脚本可以在这里findASP.NET身份 – Codeplex示例代码
这是我在vb.net中的示例工作代码
Imports System.Threading.Tasks Imports Microsoft.AspNet.Identity Namespace MyNameSpace Public Class MyPasswordValidator Inherits PasswordValidator Public Overrides Function ValidateAsync(item As String) As Task(Of IdentityResult) Dim errorMessage As String = String.Empty Dim bolminChar As Boolean = True Dim bolminDigit As Boolean = True Dim bolminLcase As Boolean = True Dim bolminUCase As Boolean = True Dim bolminNonAlfanum As Boolean = True If Not String.IsNullOrWhiteSpace(item) AndAlso item.Length >= Me.RequiredLength Then bolminChar = True Else bolminChar = False errorMessage = String.Format(CultureInfo.CurrentCulture, Resources.validator.PasswordTooShort & "<br/>", RequiredLength) End If If Me.RequireDigit Then Dim regex As New Regex("^(?=.*\d).+$") Dim match As Match = regex.Match(item) If match.Success Then bolminDigit = True Else bolminDigit = False errorMessage &= Resources.validator.PasswordRequireDigit & ".<br/>" End If End If If Me.RequireLowercase Then Dim LCrex As New Regex("^(?=.*[az]).+$") Dim LCMatch As Match = LCrex.Match(item) If LCMatch.Success Then bolminLcase = True Else bolminLcase = False errorMessage &= Resources.validator.PasswordRequireLower & "<br/>" End If End If If Me.RequireNonLetterOrDigit Then Dim NAFRex As New Regex("^(?=.*[-+_!@#$%=^\[\]\{\}()&*.,?]).+$") Dim NAFMatch As Match = NAFRex.Match(item) If NAFMatch.Success Then bolminNonAlfanum = True Else bolminNonAlfanum = False errorMessage &= Resources.validator.PasswordRequireNonLetterOrDigit & "<br/>" End If End If If Me.RequireUppercase Then Dim UCrex As New Regex("^(?=.*[AZ]).+$") Dim UCMatch As Match = UCrex.Match(item) If UCMatch.Success Then bolminUCase = True Else bolminUCase = False errorMessage &= Resources.validator.PasswordRequireUpper & "<br/>" End If End If If bolminChar And bolminDigit And bolminLcase And bolminNonAlfanum And bolminUCase Then Return Task.FromResult(Of IdentityResult)(IdentityResult.Success) Else Return Task.FromResult(Of IdentityResult)(IdentityResult.Failed(New String() {errorMessage})) End If 'Return MyBase.ValidateAsync(item) End Function End Class Public Class MyUserValidator Inherits UserValidator(Of applicationUser, int64) Private _manager As ApplicationUserManager Public Sub New(manager As ApplicationUserManager) MyBase.New(manager) _manager = manager End Sub Public Overrides Function ValidateAsync(item As applicationUser) As Task(Of IdentityResult) If item Is Nothing Then Throw New ArgumentNullException("item") End If Dim errors As New List(Of String)() Validateusername(item, errors) If Me.RequireUniqueEmail Then ValidateEmail(item, errors) End If If errors.Count > 0 Then Return Task.FromResult(Of IdentityResult)(IdentityResult.Failed(errors.ToArray())) End If Return Task.FromResult(Of IdentityResult)(IdentityResult.Success) End Function Private Sub Validateusername(User As applicationUser, errors As List(Of String)) If String.IsNullOrWhiteSpace(User.UserName) Then errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.PropertyTooShort, "Email")) ' ElseIf Me.AllowOnlyAlphanumericUserNames AndAlso Not Regex.IsMatch(User.UserName, "^[A-Za-z0-9@_\.]+$") Then ' If any characters are not letters or digits, its an illegal user name errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.InvalidUserName, User.UserName)) Else Dim owner = _manager.FindByName(User.UserName) If owner IsNot Nothing AndAlso Not EqualityComparer(Of applicationUser).ReferenceEquals(owner.Id, User.Id) Then errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.DuplicateName, User.UserName)) End If End If End Sub Private Sub ValidateEmail(User As ApplicationUser, errors As List(Of String)) Dim email As String = String.Empty If User.Id > 0 Then email = _manager.GetEmail(User.Id) End If If String.IsNullOrWhiteSpace(email) Then errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.PropertyTooShort, "Email")) Return End If Try Dim m As New MailAddress(email) Catch ex As Exception errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.InvalidEmail, email)) Return End Try Dim owner = _manager.FindByEmail(email) If owner IsNot Nothing AndAlso Not EqualityComparer(Of ApplicationUser).ReferenceEquals(owner.Id, User.Id) Then errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.validator.DuplicateName, email)) End If End Sub End Class
请记住更新您的identityConfig.vb文件中的设置以使用这些类。
我的解决scheme有点肮脏,但它按预期工作。 我们的想法是分配所有IdentityResult对象结果在注册新用户时所带来的错误:
var result = await UserManager.CreateAsync(user, model.Password);
我们将创build一个新的。 首先,我们需要创build一个包含我们自定义错误的List:
var erroresEspanol = new List<string>();
然后,我们需要遍历结果中的错误,并为每个错误添加一个新的自定义错误,具体取决于错误原因(重复的用户,电子邮件等):
foreach (var error in result.Errors) { if (error == ("Name " + model.Usuario + " is already taken.")) { erroresEspanol.Add("El Usuario " + model.Usuario + " ya existe."); } if (error.Substring(0, error.IndexOf(" ")) == "Email") { erroresEspanol.Add("El Email " + model.Email + " ya fue ingresado."); } if (error.Substring(0, error.IndexOf(" ")) == "Passwords") { erroresEspanol.Add("La contraseña debe contener mayúscula, minúscula y al menos 6 caracteres de longitud."); } }
所以之后我们只需要创build一个新的IdentityResult对象:
var resultado = new IdentityResult(erroresEspanol);
并将其传递给我们注册操作结束时的AddErrors方法:
AddErrors(resultado);
遇到同样的问题,可以提供自己的资源文件来实现这一点。 当然这需要一点反思黑客! 首先,您需要以完全安全的方式运行,即在web.config中设置:
<system.web> <securityPolicy> <trustLevel name="Full" policyFile="internal"/> </securityPolicy> ...
接下来在您的应用程序中启动代码:
var ass = Assembly.Load("Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); Type hack = ass.GetType("Microsoft.AspNet.Identity.Resources"); var field = hack.GetField("resourceMan", BindingFlags.Static | BindingFlags.NonPublic); // NOTE: this is where you set you own resource manager! field.SetValue(null, new global::System.Resources.ResourceManager("WebApplication1.Resources", typeof(WebApplication1.Resources).Assembly));
任务完成!