Web API controllers return JSON (or XML) instead of HTML views. They power SPAs, mobile apps, and microservices—RESTful routes with HTTP verbs and status codes.
ApiController basics
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
[HttpGet]
public async Task<ActionResult<List<ProductDto>>> List() { }
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDto>> Get(int id) { }
[HttpPost]
public async Task<ActionResult<ProductDto>> Create(ProductCreateDto dto) { }
}
Status codes
200 OK— success with body201 Created— useCreatedAtAction400 Bad Request— validation failures404 Not Found— missing resource204 No Content— successful DELETE
[ApiController] behaviors
Automatic model validation (400 on invalid ModelState), binding source inference, and problem details for errors.
Important interview questions and answers
- Q: REST vs RPC-style routes?
A: REST uses nouns and HTTP verbs; RPC uses action names in URLs—pick consistency for your API consumers. - Q: DTO vs entity in API?
A: Never expose EF entities directly—DTOs control shape and prevent over-posting/leaky relations.
Self-check
- Which attribute enables automatic 400 on invalid models?
- What status code fits a successful POST that creates a resource?
Tip: Return DTOs from APIs, not EF entities—prevents leaking navigation graphs and protects against over-posting on write endpoints.
Interview prep
- What does [ApiController] do?
Enables automatic model validation (400 on invalid ModelState), binding source inference, and standardized problem details for API errors.