ASP.NET Core 3.x RESTful API学习记录--获取父子关系资源
//获取父子资源关系实例 要在路由上表示出来父子关系 [ApiController] [Route("api/companies/{companyId}/employees")] public class EmployeesController : ControllerBase { private readonly IMapper _mapper; private readonly ICompanyRepository _companyRepository; public EmployeesController(IMapper mapper, ICompanyRepository companyRepository) { _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository)); } [HttpGet] public async Task<ActionResult<IEnumerable<EmployeeDto>>> GetEmployeesForCompany(Guid companyId, [FromQuery] EmployeeDtoParameters parameters) { if (!await _companyRepository.CompanyExistsAsync(companyId)) { return NotFound(); } var employees = await _companyRepository .GetEmployeesAsync(companyId, parameters); var employeeDtos = _mapper.Map<IEnumerable<EmployeeDto>>(employees); return Ok(employeeDtos); } [HttpGet("{employeeId}"] public async Task<ActionResult<EmployeeDto>> GetEmployeeForCompany(Guid companyId, Guid employeeId) { if (!await _companyRepository.CompanyExistsAsync(companyId)) { return NotFound(); } var employee = await _companyRepository.GetEmployeeAsync(companyId, employeeId); if (employee == null) { return NotFound(); } var employeeDto = _mapper.Map<EmployeeDto>(employee); return Ok(employeeDto); }
知识来源草根专栏 感谢杨旭大佬