【发布时间】: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