如何更改ASP.NET Identity中的错误消息 [英] How to change error message in ASP.NET Identity
问题描述
我有一个问题. 我正在尝试更改Identity ASP .NET中的错误消息,但我不知道该怎么做. 我想要更改错误消息-已经登录". CreateAsync方法返回此错误消息. 请帮助我.
I have one question. I'm trying change error message in Identity ASP .NET and I don't know how do it. I want change error message - "Login is already taken". CreateAsync method return this error message. Please help me.
推荐答案
Microsoft.AspNet.Identity.UserManager<TUser>
类具有一个名为UserValidator
的公共属性,类型为IIdentityValidator<TUser>
. UserManager的构造函数将该属性设置为Microsoft.AspNet.Identity.UserValidator<TUser>
的实例.您在调用CreateAsync时看到的错误消息来自Microsoft.AspNet.Identity.dll中嵌入的资源,并从UserValidator内部添加到IdentityResult中.
The Microsoft.AspNet.Identity.UserManager<TUser>
class has a public property called UserValidator
of type IIdentityValidator<TUser>
. The constructor for UserManager sets that property to an instance of Microsoft.AspNet.Identity.UserValidator<TUser>
. The error messages you see when calling CreateAsync come from the resources embedded in the Microsoft.AspNet.Identity.dll and are added to the IdentityResult from inside UserValidator.
您可以提供自己的IIdentityValidator<TUser>
实现,这只是一个带有签名:Task<IdentityResult> ValidateAsync(TUser item)
的单一方法.您必须实施自己的验证,但可以控制发出的消息.像这样:
You could provide your own implementation of IIdentityValidator<TUser>
, which is just a single method with signature: Task<IdentityResult> ValidateAsync(TUser item)
. You'd have to implement your own validations, but you'd have control over the messages that come out. Something like:
public class UserValidator : IIdentityValidator<ApplicationUser>
{
public async Task<IdentityResult> ValidateAsync(ApplicationUser item)
{
if (string.IsNullOrWhiteSpace(item.UserName))
{
return IdentityResult.Failed("Really?!");
}
return IdentityResult.Success;
}
}
默认的UserValidator类执行三个基本验证,如果您自己滚动,请牢记:
The default UserValidator class performs three basic validations to keep in mind if you roll your own:
- 用户名不为null或空格
- 用户名是字母数字
- 用户名不是重复的
这篇关于如何更改ASP.NET Identity中的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!