1

I am using this to add a newly created user, to role:

var db = new ApplicationDbContext();
ApplicationDbContext context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);

userManager.AddToRole(user.Id, model.UserRole);

In my solution username = email.

I have discovered, when the username/email contains a sign (+, - or anything like that), it will not add the user to a role. The error i get is "User name x is invalid, can only contain letters or digits.". The user gets added succesfully, it is just the AddToRole, that fails.

But i cannot figure out why.

AllowOnlyAlphanumericUserNames is set to false, in IdentityConfig.cs

Any ideas?

4

3 回答 3

5

There are two possible solutions I can think of.

1.) Follow the solution you linked in the comments by editing your code sample to this:

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
userManager.AddToRole(user.Id, model.UserRole);

2.) Re-create the UserValidator in your userManager and attempt to AddToRole again:

var db = new ApplicationDbContext();
ApplicationDbContext context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true };
userManager.AddToRole(user.Id, model.UserRole);
于 2016-03-29T13:37:19.153 回答
1

I think the problem is, that you are creating a new instance of UserManager and not using the one if the IdentityConfig . Try to set userManager.AllowOnlyAlphanumericUserNames = false; after the line var userManager = new UserManager<ApplicationUser>(userStore); of your code

于 2016-03-29T13:35:22.763 回答
0

Make AllowOnlyAlphanumericUserNames as false by adding the code below and this works out.

  userManager.UserValidator = new UserValidator<User>(userManager)
        {
            AllowOnlyAlphanumericUserNames = false
        };
于 2019-04-09T18:07:59.393 回答