使用web api 2和标识2,我试图创建一个操作,使用用户id和角色名称将用户从角色中删除。我使用的是nugetidentity2示例提供的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);
}
我的问题是,如果用户属于"user"one_answers"Mod"角色,则无法将该用户从"Mod(中删除。发布以下json会按预期将用户从"用户"角色中删除:
{
"userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
"roleNames": [
"User"
]
}
但给定以下json,用户不会从"Mod"中删除,而是从"user"中删除:
{
"userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
"roleNames": [
"Mod"
]
}
调试显示,当给定角色"Mod"时,正确的用户id和角色名称会传递到userRoleStore中。
这是一个应该在2.0.1版本中修复的错误
//丑陋但能正常使用
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));