AddToRole失败,用户名中带有+号?

时间:2016-03-29 12:42:59

标签: c# asp.net asp.net-identity asp.net-authentication

我使用它将新创建的用户添加到角色:

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);

在我的解决方案中,username = email。

我发现,当用户名/电子邮件包含一个符号(+, - 或类似的东西)时,它不会将用户添加到角色中。我得到的错误是&#34; User name x is invalid, can only contain letters or digits.&#34;。 用户成功添加,只是AddToRole,失败。

但我无法弄明白为什么。

在IdentityConfig.cs中

AllowOnlyAlphanumericUserNames设置为false

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

我能想到两种可能的解决方案。

1。)通过编辑代码示例来关注the solution you linked in the comments

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

2.。)重新设置UserValidator中的userManager并再次尝试AddToRole

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);

答案 1 :(得分:1)

我认为问题是,您正在创建 UserManager 的新实例,而不是使用 IdentityConfig 的实例。尝试设置 android:launchMode="singleTop"代码行userManager.AllowOnlyAlphanumericUserNames = false;之后

答案 2 :(得分:0)

是的,这可行:

    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();
    }