Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

c# - Web Api: get child entities

I am new to Web Apis (I have an ASP.NET Core Web application with some Apis)

Suppose we have Company/Employee and we want to get all employees for a Company via an API.

I have Company controller and I would like to return Employees.

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);
    }
}
question from:https://stackoverflow.com/questions/65934743/web-api-get-child-entities

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here

More detail information about routing in asp.net core, you can refer the following links:

Routing to controller actions in ASP.NET Core


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...