직원을 삭제하려면 URI /api/employees/ID 에 HTTP DELETE 요청을 사용합니다. 삭제할 직원의 ID를 URI에 전달해야 합니다 .
ASP.NET Core REST API – HTTP 삭제 예시
[Route("api/[controller]")] [ApiController] public class EmployeesController : ControllerBase { private readonly IEmployeeRepository employeeRepository; public EmployeesController(IEmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } [HttpDelete("{id:int}")] public async Task<ActionResult<Employee>> DeleteEmployee(int id) { try { var employeeToDelete = await employeeRepository.GetEmployee(id); if (employeeToDelete == null) { return NotFound($"Employee with Id = {id} not found"); } return await employeeRepository.DeleteEmployee(id); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error deleting data"); } } }
코드 설명
기존 직원을 삭제하는 데 사용되는 DELETE 요청입니다. 이것이 DeleteEmployee() 메서드가 HttpDelete 속성 으로 Decorate 된 이유입니다 .
삭제할 직원의 ID는 HttpDelete 속성에 매개변수로 전달 됩니다 . 이 ID는 URL /api/employees 에 추가됩니다 . 따라서 URL은 /api/employees/id 가 됩니다.
[HttpDelete("{id:int}")] public async Task<ActionResult<Employee>> DeleteEmployee(int id)
URL의 직원 ID 값은 DeleteEmployee ( int id) 메서드 의 id 매개 변수에 자동으로 매핑됩니다 .
id 경로 매개 변수 에 int 경로 제약 조건을 사용하므로 URL의 id 값은 값이 정수인 경우에만 메서드 매개 변수에 매핑됩니다.
ASP.NET Core 웹 API CRUD 작업 예제
다음은 전체 EmployeesController 코드입니다. CRUD 작업을 구현한 예제입니다.
using EmployeeManagement.Api.Models; using EmployeeManagement.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace EmployeeManagement.Api.Controllers { [Route("api/[controller]")] [ApiController] public class EmployeesController : ControllerBase { private readonly IEmployeeRepository employeeRepository; public EmployeesController(IEmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } [HttpGet] public async Task<ActionResult> GetEmployees() { try { return Ok(await employeeRepository.GetEmployees()); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database"); } } [HttpGet("{id:int}")] public async Task<ActionResult<Employee>> GetEmployee(int id) { try { var result = await employeeRepository.GetEmployee(id); if (result == null) { return NotFound(); } return result; } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database"); } } [HttpPost] public async Task<ActionResult<Employee>> CreateEmployee(Employee employee) { try { if(employee == null) { return BadRequest(); } var emp = employeeRepository.GetEmployeeByEmail(employee.Email); if(emp != null) { ModelState.AddModelError("email", "Employee email already in use"); return BadRequest(ModelState); } var createdEmployee = await employeeRepository.AddEmployee(employee); return CreatedAtAction(nameof(GetEmployee), new { id = createdEmployee.EmployeeId }, createdEmployee); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database"); } } [HttpPut("{id:int}")] public async Task<ActionResult<Employee>> UpdateEmployee(int id, Employee employee) { try { if(id != employee.EmployeeId) { return BadRequest("Employee ID mismatch"); } var employeeToUpdate = await employeeRepository.GetEmployee(id); if(employeeToUpdate == null) { return NotFound($"Employee with Id = {id} not found"); } return await employeeRepository.UpdateEmployee(employee); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error updating data"); } } [HttpDelete("{id:int}")] public async Task<ActionResult<Employee>> DeleteEmployee(int id) { try { var employeeToDelete = await employeeRepository.GetEmployee(id); if (employeeToDelete == null) { return NotFound($"Employee with Id = {id} not found"); } return await employeeRepository.DeleteEmployee(id); } catch (Exception) { return StatusCode(StatusCodes.Status500InternalServerError, "Error deleting data"); } } } }
EmployeeRepository
EmployeeRepository는 엔터티 프레임워크 코어를 사용하여 SQL Server 데이터베이스에서 데이터를 저장하고 검색합니다.
public class EmployeeRepository : IEmployeeRepository { private readonly AppDbContext appDbContext; public EmployeeRepository(AppDbContext appDbContext) { this.appDbContext = appDbContext; } public async Task<Employee> AddEmployee(Employee employee) { var result = await appDbContext.Employees.AddAsync(employee); await appDbContext.SaveChangesAsync(); return result.Entity; } public async Task<Employee> DeleteEmployee(int employeeId) { var result = await appDbContext.Employees .FirstOrDefaultAsync(e => e.EmployeeId == employeeId); if (result != null) { appDbContext.Employees.Remove(result); await appDbContext.SaveChangesAsync(); return result; } return null; } public async Task<Employee> GetEmployee(int employeeId) { return await appDbContext.Employees .FirstOrDefaultAsync(e => e.EmployeeId == employeeId); } public async Task<Employee> GetEmployeeByEmail(string email) { return await appDbContext.Employees .FirstOrDefaultAsync(e => e.Email == email); } public async Task<IEnumerable<Employee>> GetEmployees() { return await appDbContext.Employees.ToListAsync(); } public async Task<Employee> UpdateEmployee(Employee employee) { var result = await appDbContext.Employees .FirstOrDefaultAsync(e => e.EmployeeId == employee.EmployeeId); if (result != null) { result.FirstName = employee.FirstName; result.LastName = employee.LastName; result.Email = employee.Email; result.DateOfBrith = employee.DateOfBrith; result.Gender = employee.Gender; result.DepartmentId = employee.DepartmentId; result.PhotoPath = employee.PhotoPath; await appDbContext.SaveChangesAsync(); return result; } return null; } }