0

The code below is called to assign the current authenticated user to a role named Admin. The user has already been created with a correctly configured email address and I can authenticate with it. However, I want to add the user to a Role using the demo code below.

public ActionResult AddUserToRole()
{
    var userId = User.Identity.GetUserId();
    using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
        IdentityResult result = userManager.AddToRole(userId, "Admin");
     }
     return RedirectToAction("Index");
}

The user was created using the template code from a new MVC 5 application. The template code calls for an email address for the username. However, the result of the AddToRole line returns result.Succeeded = false with an error of

User name jason@xxxxxxx.xx.xx is invalid, can only contain letters or digits.

Why does the call to role apply the validator but the call to create a user doesn't? It's all template code.

Now, given that this is all template code, am I missing something or do I need to modify the template to have the user supply a username that isn't an email address.

Many thanks.

Jason James
  • 1,082
  • 1
  • 14
  • 27
  • 1
    it seems your context or database is configured in a way that doesn't allow dots and/or '@' symbols in your user name property. – DevilSuichiro Jul 30 '16 at 14:41
  • Duplicate http://stackoverflow.com/questions/19460078/configure-microsoft-aspnet-identity-to-allow-email-address-as-username – Steve Greene Jul 30 '16 at 14:49
  • The username was set up perfectly as an email. Only adding the user to a role caused the problem. – Jason James Jul 30 '16 at 14:50

1 Answers1

1

I had the same problem. To get around it, add the following line, before calling AddToRole():

        userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false };

Someone may know a more elegant solution, but this worked for me, so I never investigated further!

HTH