Jason James
Jason James

Reputation: 1092

Add user to role where username is email address

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 [email protected] 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.

Upvotes: 0

Views: 80

Answers (1)

user6638270
user6638270

Reputation:

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

Upvotes: 1

Related Questions