public async Task <IActionResult> EditUser([FromRoute] string userId, [FromBody] EditUserDto editUserDto) { if (!ModelState.IsValid || string.IsNullOrWhiteSpace(editUserDto.UserName) && string.IsNullOrWhiteSpace(editUserDto.Email)) { return(BadRequest(ModelState)); } // Check if the user exists var exists = await _context.AppUsers.AnyAsync(usr => usr.Id == userId); if (!exists) { return(NotFound()); } // Check if the username conflicts with existing ones var foundUser = await _context.AppUsers.AsNoTracking().SingleAsync(user => user.Id == userId); if (!string.IsNullOrWhiteSpace(editUserDto.UserName)) { var usernameExists = await _context.AppUsers.AnyAsync(usr => usr.UserName == editUserDto.UserName); if (usernameExists) { return(Conflict("Username exists")); } foundUser.UserName = editUserDto.UserName; } // Check if the email conflicts with existing ones if (!string.IsNullOrWhiteSpace(editUserDto.Email)) { var emailExists = await _context.AppUsers.AnyAsync(usr => usr.Email == editUserDto.Email); if (emailExists) { return(Conflict("Email exists")); } foundUser.Email = editUserDto.Email; } // Save the changes await _appUsersService.Edit(foundUser); // Form the HAL response var response = new GetUserResponse( foundUser, LinkGenerator.Users.Edit(foundUser.Id, "self") ); return(Ok(response)); }