How to change error message in ASP.NET Identity

心不动则不痛 提交于 2019-12-04 18:07:01

问题


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.


回答1:


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:

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



回答2:


private void AddErrors(IdentityResult result)
{
    foreach (var error in result.Errors)
    {
        if (error.StartsWith("Name"))
        {
            var NameToEmail= Regex.Replace(error,"Name","Email");
            ModelState.AddModelError("", NameToEmail);
        }
        else
        {
            ModelState.AddModelError("", error);
        }
    }
}


来源:https://stackoverflow.com/questions/20919884/how-to-change-error-message-in-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!