private void AssignRoles(string userId, Roles roles) { foreach (var role in roles.UserRoles) { //get roleid var roleId = _client.GetAsync("roles") .Result .Content .ReadAsAsync<List<IdentityRole>>() .Result .First(r => r.Name.Equals(role)) .Id; var addUserToRoleModel = new UserToRoleModel { RoleId = roleId, UserId = userId }; //add user to role var response = _client.PostAsync("roles/addusertorole", addUserToRoleModel, new JsonMediaTypeFormatter()).Result; if (!response.IsSuccessStatusCode) { throw new Exception($"{response.StatusCode} - {response.ReasonPhrase}"); } } }
public async Task<IHttpActionResult> AddUserToRole(UserToRoleModel model) { var role = await RoleManager.FindByIdAsync(model.RoleId); if (role == null) { ModelState.AddModelError("", "Role does not exist"); return BadRequest(ModelState); } var user = await UserManager.FindByIdAsync(model.UserId); if(!UserManager.IsInRole(user.Id, role.Name)) { var result = await UserManager.AddToRoleAsync(user.Id, role.Name); if (!result.Succeeded) { ModelState.AddModelError("", $"User: {user} could not be added to role"); } } if (!ModelState.IsValid) { return BadRequest(ModelState); } return Ok(); }