【问题标题】:Can't remove users from specific role无法从特定角色中删除用户
【发布时间】:2014-04-30 22:58:16
【问题描述】:

使用 web-api 2 和身份 2,我正在尝试创建一个操作,以使用用户 ID 和角色名称从角色中删除用户。我正在使用 nuget identity2 示例提供的 ApplicationUserManager。

我的行动

[HttpPost]
[Route("RemoveUserFromRole")]
public async Task<IHttpActionResult> RemoveUserFromRole(UserRolesViewModel model) 
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var result = await UserManager.RemoveUserFromRolesAsync(
        model.UserId, model.RoleNames);

    if (result.Errors.Any())
        return InternalServerError(); 

    return Ok();
}

我的视图模型:

public class UserRolesViewModel
{
    [Required]
    public string UserId { get; set; }

    [Required]
    public IList<string> RoleNames { get; set; }
}

ApplicationUserManager 的 RemoveUserFromRolesAsync:

public virtual async Task<IdentityResult> RemoveUserFromRolesAsync(
    string userId, IList<string> roles) 
{
    var userRoleStore = (IUserRoleStore<ApplicationUser, string>) Store;

    var user = await FindByIdAsync(userId).ConfigureAwait(false);
    if (user == null)
        throw new InvalidOperationException("Invalid user Id");

    var userRoles = await userRoleStore.GetRolesAsync(user).ConfigureAwait(false);
    foreach (var role in roles.Where(userRoles.Contains))
        await userRoleStore.RemoveFromRoleAsync(user, role).ConfigureAwait(false);

    return await UpdateAsync(user).ConfigureAwait(false);
}

我的问题是,如果用户属于角色“用户”和“模组”,则无法从“模组”中删除该用户。发布以下 json 会按预期将用户从角色“用户”中删除:

{
    "userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
    "roleNames": [
        "User"
    ]
}

但鉴于以下 json,用户并未从“Mod”中删除,而是从“用户”中删除:

{
    "userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
    "roleNames": [
        "Mod"
    ]
}

调试显示,当给定角色“Mod”时,正确的用户 ID 和角色名称被传递到 userRoleStore。

【问题讨论】:

    标签: c# asp.net asp.net-web-api asp.net-identity


    【解决方案1】:

    这是一个应该在 2.0.1 版本中修复的错误

    【讨论】:

    • 谢谢 - 你有这个的来源吗?
    • 啊 - 我在我的主要项目中更新到 2.0.1,但在我的测试中忘记并停留在 2.0。再次感谢
    【解决方案2】:

    //丑但有效

    db.Database.ExecuteSqlCommand(@"delete from aspnetuserroles from
    aspnetuserroles ur inner join aspnetroles r on r.id=ur.roleid inner join aspnetusers 
    u on u.id=ur.userid where r.name=@role and u.username=@user",
        new SqlParameter("@role",RoleName) ,
        new SqlParameter("@user",UserName));
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2022-10-17
      • 2021-08-12
      • 1970-01-01
      • 2021-09-06
      • 2019-11-01
      • 2015-12-17
      • 2021-03-28
      • 1970-01-01
      相关资源
      最近更新 更多