I'm trying to change the error message in Identity ASP .NET and I don't know how to do it. I want to change the error message to this: "Login is already taken". CreateAsync method should return this error message.
-
1See also stackoverflow.com/questions/19961648/…Funka– Funka2014-05-28 18:26:04 +00:00Commented May 28, 2014 at 18:26
-
I´ve post an answer for almost the same thing here: stackoverflow.com/questions/19961648/…Ignacio– Ignacio2015-06-08 13:29:10 +00:00Commented Jun 8, 2015 at 13:29
2 Answers
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.
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;
}
}
The default UserValidator class performs three basic validations to keep in mind if you roll your own:
- UserName is not null or whitespace
- UserName is alphanumeric
- UserName is not a duplicate