public async Task <IHttpActionResult> AssignRolesToUser([FromUri] string id, [FromBody] AssignRolesModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _usersService.FindByIdAsync(id); if (user == null) { return(NotFound()); } var currentRoles = await _usersService.GetRolesAsync(user.Id); var incorrectRoles = model.NewRoles.Except(_rolesService.GetRoles().Select(x => x.Name)).ToArray(); if (incorrectRoles.Count() > 0) { ModelState.AddModelError(string.Empty, $"Roles '{string.Join(",", incorrectRoles)}' does not exist in the system"); return(BadRequest(ModelState)); } IdentityResult removeResult = await _usersService.RemoveFromRolesAsync(user.Id, currentRoles.ToArray()); if (!removeResult.Succeeded) { ModelState.AddModelError(string.Empty, "Failed to remove user roles"); return(BadRequest(ModelState)); } IdentityResult addResult = await _usersService.AddToRolesAsync(user.Id, model.NewRoles); if (!addResult.Succeeded) { ModelState.AddModelError(string.Empty, "Failed to add user roles"); return(BadRequest(ModelState)); } return(Ok($"Roles '{string.Join(",", model.NewRoles)}' added to user {id}")); }