Suppose we want to get the employees via something like
/company/{id}/employees
Is it correct like the following controller is formed :
public class CompanyController {
[Route("/company/{id}/employees")]
public async Task<IActionResult> Employees(int id) {
var company = await _repository.GetByIdAsync<Company>(id);
return Ok(company.Employees);
}
}
Yes, you can use the above route, then, the request URL should like this: https://localhost:44312/company/12/employees
[Note] The Request URL doesn't contain the api
.
Besides, if you want to add the api
in the request url, you can also use the route configure:
[Route("api/[controller]")]
[ApiController]
public class CompanyController : ControllerBase
{
// GET api/<CompanyController>/5/employees
[HttpGet("{id}/employees")]
public string Get(int id)
{
//query database and get the company and related employees. Refer: https://docs.microsoft.com/en-us/ef/core/querying/related-data/
return "Entered companyid value: "+ id;
}
Then, the request URL like this: https://localhost:44312/api/company/12/employees
.
You could check the following screenshot:
More detail information about routing in asp.net core, you can refer the following links:
Routing to controller actions in ASP.NET Core
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…