我目前正在构建一个 RESTful Web API,以便可以从应用程序中的角色中删除用户。
这是UsersController
(API(:
public class UsersController : ApiController
{
private ApplicationDbContext _identity;
private readonly UserManager<ApplicationUser> _userManager;
public UsersController()
{
_identity = new ApplicationDbContext();
var store = new UserStore<ApplicationUser>(_identity);
_userManager = new UserManager<ApplicationUser>(store);
}
// --- REMOVE USER FROM ROLE HERE ---
[HttpDelete]
[Route("api/users/{userId}/roles/{roleName}")]
public async void RemoveFromRole(string userId, string roleName)
{
var userInDb = _identity.Users.SingleOrDefault(u => u.Id == userId);
if (userInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
var roleInDb = _identity.Roles.SingleOrDefault(r => r.Name == roleName);
if (roleInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
await _userManager.RemoveFromRoleAsync(userInDb.Id, roleInDb.Id);
}
我在视图中使用此 AJAX 请求调用RemoveFromRole
方法:
$("#roles").on("click", ".js-delete", function() {
var button = $(this);
bootbox.confirm("Are you sure you want to remove the user from this role?",
function(result) {
if (result) {
$.ajax({
url: "/api/users/" +
button.attr("data-user-id") +
"/roles/" +
button.attr("data-role-name"),
method: "DELETE",
success: function() {
location.reload();
toastr.success("Role removed");
},
error: function() {
toastr.error("Unable to remove user from role");
}
});
}
});
});
但是,在运行此操作时,RemoveFromRoleAsync
不成功(结果。成功 = false(,因此不会从角色中删除用户。
我是使用 ASP 标识的新手,我认为我可能不正确地使用了UserManager
/UserStore
。
用户管理器有一个方法Task<IList<string>> GetRolesAsync(TKey userId)
返回用户的角色
使用它来获取为用户分配的角色。确认该用户存在要删除的角色,然后使用用户管理器将其删除。
[HttpDelete]
[Route("api/users/{userId}/roles/{roleName}")]
public async Task<IHttpActionResult> RemoveFromRole(string userId, string roleName) {
var userInDb = _identity.Users.FirstOrDefault(user => user.Id == userId);
if (userInDb == null)
return NotFound();
//get user's assigned roles
IList<string> userRoles = await _userManager.GetRolesAsync(userId);
//check for role to be removed
var roleToRemove = userRoles.FirstOrDefault(role => role.Equals(roleName, StringComparison.InvariantCultureIgnoreCase));
if (roleToRemove == null)
return NotFound();
var result = await _userManager.RemoveFromRoleAsync(userId, roleToRemove);
if(result.Succeeded)
return Ok();
return BadRequest();
}
请注意,该操作也进行了重构,以遵循文档中的建议语法