How to change error message in ASP.NET Identity

后端 未结 2 980
梦毁少年i
梦毁少年i 2021-02-13 13:24

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 m

2条回答
  •  抹茶落季
    2021-02-13 14:00

    The Microsoft.AspNet.Identity.UserManager class has a public property called UserValidator of type IIdentityValidator. The constructor for UserManager sets that property to an instance of Microsoft.AspNet.Identity.UserValidator. 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, which is just a single method with signature: Task 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
    {
        public async Task 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:

    1. UserName is not null or whitespace
    2. UserName is alphanumeric
    3. UserName is not a duplicate

提交回复
热议问题