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

问题描述 投票:1回答:3

我使用它来添加一个新创建的用户,角色:

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。

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

但我无法弄清楚为什么。

在IdentityConfig.cs中,AllowOnlyAlphanumericUserNames设置为false

有任何想法吗?

c# asp.net asp.net-identity asp.net-authentication
3个回答
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
投票

我认为问题是,您正在创建UserManager的新实例,而不是使用IdentityConfig中的实例。尝试在代码行userManager.AllowOnlyAlphanumericUserNames = false;之后设置var userManager = new UserManager<ApplicationUser>(userStore);


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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.