无法从特定角色中删除用户

时间:2014-04-30 22:58:16

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

使用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);
}

我的问题是,如果用户属于角色&#39;用户&#39;和&#39; Mod&#39;,用户无法从&#39; Mod&#39;中删除。发布以下json会将用户从角色&#39; User&#39;中删除。正如所料:

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

但是考虑到以下json,用户不会从&#39; Mod&#39;中删除,而是从&#39; User&#39;中删除:

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

调试显示,当给定角色&#39; Mod&#39;时,正确的用户ID和角色名称将传递到userRoleStore。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

//丑陋但有效

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