ASP.NET MVC Identity Email/Username with Special C

2019-04-07 16:54发布

问题:

When registering an account through Web API with an email such as "xxx-yyy@gmail.com", Fiddler returns the follow error. Note that email is used for username as well, so both fields are the same. But it works when registering on MVC itself.

ExceptionMessage=User Creation Failed - Identity Exception. Errors were:

User name xx-yyy@gmail.com is invalid, can only contain letters or digits.

User Object

 var newUser = new ApplicationUser {
            UserName = user.Email,
            Email = user.Email
        };

IdentifyConfig.cs

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager) {
            RequireUniqueEmail = true,
            AllowOnlyAlphanumericUserNames = false

        };

I have tried commenting out AllowOnlyAlphanumericUserNames but it didn't work. By right setting it to false should allow special characters, in my case a hyphen(-).

API Controller

// POST: api/auth/register
    [ActionName("Register")]
    public async Task<HttpResponseMessage> PostRegister(Auth user) {


        //dash issue is here. 

        var userContext = new ApplicationDbContext();

        var userStore = new UserStore<ApplicationUser>(userContext);

        var userManager = new UserManager<ApplicationUser>(userStore);

        var newUser = new ApplicationUser {
            UserName = user.Email,
            Email = user.Email
        };

        var result = await userManager.CreateAsync(newUser, user.PasswordHash);

        if (result.Succeeded) {
        ...

Solution

There is NO changes to IdentityConfig.cs. Only changes is to my API Controller.

  // POST: api/auth/register
        [ActionName("Register")]
        public async Task<HttpResponseMessage> PostRegister(Auth user) {

//Changed to the following line
            ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

            var newUser = new ApplicationUser {
                UserName = user.Email,
                Email = user.Email
            };

            var result = await userManager.CreateAsync(newUser, user.PasswordHash);

回答1:

You are setting AllowOnlyAlphanumericUserNames = false in Create method of ApplicationUserManager. Inside the PostRegister action of your ApiController you are newing an instance of ApplicationUserManager. AllowOnlyAlphanumericUserNames is true by default.

You can change the Constructor of ApplicationUserManager

public ApplicationUserManager(IUserStore<ApplicationUser> store): base(store)
{
      UserValidator = new UserValidator<ApplicationUser>(this)
      {
           AllowOnlyAlphanumericUserNames = false,
           RequireUniqueEmail = true
      };
}

That way AllowOnlyAlphanumericUserNames is set to false when you new an instance of ApplicationUserManger.

Note: Its better to get the ApplicationUserManager from OwinContext same as done in AccountController of default MVC5 template or use Dependency Injection.



回答2:

That's because all your config is in ApplicationUserManager, which you aren't using in your Web Api action. Instead, you're newing up plain-old UserManager, which will then use the defaults for all the validation and such.