AddToRole() returns “User name can only contain letters or digits” only when users email address contains a dash

烈酒焚心 提交于 2019-12-06 03:11:55

According to your code AllowOnlyAlphanumericUserNames = false only calling when you calling the method 'Create' of ApplicationUserManager. So that you make sure that method calls before accessing um.AddToRole() method.

Get userManager from owin context like below then call your menthods.

var userManager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();

userManager.AddToRole() etc.

Hope this helps.

Please study and follow this code, it works:

 public void AddUserToGroup(string userId, int groupId)
    {
        Group group = _db.Groups.Find(groupId);
        User user = _db.Users.Find(userId);

        var userGroup = new UserGroup
        {
            Group = group,
            GroupId = group.Id,
            User = user,
            UserId = user.Id
        };

        #region turning off Alphanumeric since we are using email in username
        var db = new DBModel();
        DBModel context = new DBModel();
        var userStore = new UserStore<User>(context);
        var userManager = new UserManager<User>(userStore);
        userManager.UserValidator = new UserValidator<User>(userManager)
        {
            AllowOnlyAlphanumericUserNames = false
        };
        #endregion
        foreach (RoleGroup role in group.Roles)
        {
            var test = userManager.AddToRole(userId, role.Role.Name);
        }
        user.Groups.Add(userGroup);
        _db.SaveChanges();
    }

I was having the same issue - however I didn't have access to Context but you can get it through the HTTP request as well, so hopefully this helps someone else with the same issue. The code I used is as follows:

userManager = OwinContextExtensions.GetUserManager<ApplicationUserManager>(this.HttpContext.GetOwinContext());

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!