public async Task <IActionResult> AddRemove([FromBody] AddRemoveRoleRequest addRemoveRoleRequest)
        {
            try
            {
                IdentityRole role = await _roleManager.FindByIdAsync(addRemoveRoleRequest.RoleId);

                if (role == null)
                {
                    throw new Exception("Role not found");
                }

                var user = await _userManager.FindByIdAsync(addRemoveRoleRequest.UserId);

                if (user == null)
                {
                    throw new Exception("User not found");
                }

                if (addRemoveRoleRequest.Add)
                {
                    await _userManager.AddToRoleAsync(user, role.Name);
                }
                else
                {
                    await _userManager.RemoveFromRoleAsync(user, role.Name);
                }

                return(Ok(true));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Get error: {ex.Message} - UserId: {addRemoveRoleRequest.UserId} - RoleId: {addRemoveRoleRequest.RoleId}");
                return(BadRequest());
            }
        }
Beispiel #2
0
        public async Task <IActionResult> AddOrRemoveRoleUser(string roleId, string userId, AddRemoveRoleRequest addRemoveRoleRequest)
        {
            if (roleId != addRemoveRoleRequest.RoleId)
            {
                return(BadRequest());
            }

            if (userId != addRemoveRoleRequest.UserId)
            {
                return(BadRequest());
            }

            var role = await _roleManager.FindByIdAsync(addRemoveRoleRequest.RoleId);

            if (role == null)
            {
                return(NotFound());
            }

            var user = await _userManager.FindByIdAsync(addRemoveRoleRequest.UserId);

            if (user == null)
            {
                return(NotFound());
            }

            try
            {
                if (addRemoveRoleRequest.Add)
                {
                    await _userManager.AddToRoleAsync(user, role.Name);
                }
                else
                {
                    await _userManager.RemoveFromRoleAsync(user, role.Name);
                }
            }
            catch (DbUpdateConcurrencyException) when(!_roleManager.Roles.AsNoTracking().Any(r => r.Id == addRemoveRoleRequest.RoleId) || !_userManager.Users.AsNoTracking().Any(u => u.Id == addRemoveRoleRequest.UserId))
            {
                return(NotFound());
            }

            return(Ok(true));
        }