I'm using Asp.Net Identity 2.0, configured so that the users' email address is also the username, so in IdentityConfig I have set AllowOnlyAlphanumericUserNames = false
in the ApplicationUserManager constructor:
public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } 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) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // ... other options removed } }
I'm using this code in a page for staff to search for a user and add a role to the user's account when checking a checkbox in a GridView of all available roles:
//protected UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); //changed this to call the ApplicationUserManager instead of UserManager to make sure AllowOnlyAlphanumericUserName = false is called, but still no luck protected ApplicationUserManager um = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext())); protected void cbRole_CheckChanged(object sender, EventArgs e) { string UserName = lblUsername.Text; if (!String.IsNullOrEmpty(UserName)) { CheckBox cb = (CheckBox)sender; GridViewRow row = (GridViewRow)cb.NamingContainer; string Role = row.Cells[1].Text; if (cb.Checked) { var user = um.FindByName(UserName); var UserResult = um.AddToRole(user.Id, Role); if (UserResult.Succeeded) { lblRoles.Text = "The <b>" + Role + "</b> role has been added for " + UserName; } else { foreach (var error in UserResult.Errors) lblRoles.Text += error; //<-- RETURNS ERROR: "User name <email address> is invalid, can only contain letters or digits." If <email address> contains a dash (-). } } else { um.RemoveFromRole(hfAspUserID.Value, Role); lblRoles.Text = "The <b>" + Role + "</b> role has been removed for " + UserName; } } }
It usually works perfectly. However, whenever a user has a dash in their username, for example "users.name@domain-name.com," the AddToRole() function returns the error User name users.name@domain-name.com is invalid, can only contain letters or digits.
All accounts are local accounts, it's NOT configured to use external logins such as facebook or Google.
Any help you can offer would be greatly appreciated, as my extensive Google search for this problem has come up with nothing other than tutorials on how to implement email addresses as usernames, which I have already done.