【问题标题】:Adding and not Updating User Roles添加和不更新用户角色
【发布时间】:2017-09-29 04:42:26
【问题描述】:

我正在尝试从下拉列表中更新用户角色。当我选择要分配的用户名(电子邮件地址)和角色(例如超级用户、管理员、用户)并点击提交时,我会按应有的方式提交所有内容。我发现,对于我为同一用户选择的要更新的角色,它会为该角色创建一个数据条目,并多次添加该用户。这使得最后输入的记录始终是 userRole。

我想不通的是,一旦我找到了用户,如何删除当前的 RoleId 并添加新的。

如果您想要 View、Model 或其他任何其他代码,请告诉我并发布。

底部的图像,例如数据库中发生的事情。

控制器

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RegisterRole(RegisterViewModel model, ApplicationUser user)
    {

        var userId = db.AspNetUsers.Where(i => i.UserName == user.UserName).Select(s => s.Id);
        string updateId = "";
        foreach (var i in userId)
        {
            updateId = i.ToString();
        }
        //Assign Role to user here
        await this.UserManager.AddToRoleAsync(updateId, model.Name);

        return RedirectToAction("Index", "Employee");
    }

【问题讨论】:

    标签: c# asp.net-mvc-5


    【解决方案1】:

    有两种方法可以派上用场:1) GetRolesAsync 获取所有用户角色,2) 在添加新角色之前使用 RemoveFromRoleAsync 将它们全部删除

    var roles = await this.UserManager.GetRolesAsync(userId);
    await this.UserManager.RemoveFromRolesAsync(userId, roles.ToArray());
    
    //then add new role 
    await this.UserManager.AddToRoleAsync(userId, roleName);
    

    编辑:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RegisterRole(RegisterViewModel model, ApplicationUser user)
    {
    
        //in case user is being passed in without Id (unlikely), you could use user manager to get the full user object 
        //user = await this.UserManager.FindByNameAsync(user.UserName);
    
        //get all user's roles, and remove them
        var roles = await this.UserManager.GetRolesAsync(user.Id);
        await this.UserManager.RemoveFromRolesAsync(user.Id, roles.ToArray());
    
        //Assign Role to user here
        await this.UserManager.AddToRoleAsync(user.Id, model.Name);
    
        return RedirectToAction("Index", "Employee");
    }
    

    【讨论】:

    • 我会把这些放在 foreach 循环之后正确吗?
    • 是的,但你为什么要运行 foreach?似乎您已经获得了一个用户,所以您可以使用 user.Id 作为 userId。我要编辑我的答案。
    • 像冠军一样工作!谢谢你,先生!我唯一需要更改的是将FindUserByNameAsync 代码行更改为to FindByNameAsync
    • 很高兴我能帮上忙,我会编辑我的答案来做出改变。
    猜你喜欢
    • 2011-07-29
    • 1970-01-01
    • 2015-03-27
    • 2015-05-18
    • 1970-01-01
    • 2016-02-11
    • 2014-11-02
    • 2013-11-11
    • 2016-07-30
    相关资源
    最近更新 更多