REST API with controllers
A controller groups the HTTP endpoints for one resource (products) into one class. Returning ActionResult<T> lets each action send the right status code with the data: 200, 201 + Location, 204 or 404.
45.1 Why is it used?
- Standard REST shape: GET list, GET by id, POST create, PUT update, DELETE, all under one route prefix.
- [ApiController] adds API behaviour: body binding from JSON, automatic 400 for invalid models, ProblemDetails for errors.
- Correct status codes let clients react properly (404 vs 204, 201 with Location).
- Very common in large projects; fully supported alongside Minimal APIs.
45.2 The bug: a plain return type
C#
using Microsoft.AspNetCore.Mvc; [ApiController][Route("api/products")]public class ProductsController( ProductStore store) : ControllerBase{ [HttpGet("{id}")] public Product? GetById(int id) => store.Find(id); [HttpPost] public Product Create(Product product) => store.Add(product);}Output
$ curl -i localhost:5000/api/products/99HTTP/1.1 204 No ContentServer: Kestrel $ curl -i localhost:5000/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Pressure Cooker","price":1899}'HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"id":3,"name":"Pressure Cooker","price":1899,"costPrice":0}- The action returns only a Product, so the framework has data but no way to choose the status code.
- Returning null becomes 204 No Content instead of 404.
- Create sends 200 with no Location header, and the entity leaks costPrice.
- Step 1
1.Action returns only Product: no control of status
- Step 2
2.store.Find(99) returns null
- Step 3
3.Framework turns null into 204, not 404
- Step 4
4.Create also sends 200, no Location
We need data + status = ActionResult
45.3 Program.cs: turn on controllers
C#
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers();builder.Services.AddSingleton<ProductStore>(); var app = builder.Build(); app.MapControllers(); app.Run();Output
$ dotnet run --urls http://localhost:5000info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5000info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.- AddControllers registers the services controllers need.
- ProductStore is a singleton, so every request shares one in-memory list.
- MapControllers reads the route attributes and creates the endpoints.
45.4 Fix: [ApiController] + GET list
C#
using Microsoft.AspNetCore.Mvc; [ApiController][Route("api/products")]public class ProductsController( ProductStore store) : ControllerBase{ [HttpGet] public IEnumerable<ProductDto> GetAll() => store.All().Select(p => p.ToDto());}Output
$ curl -i localhost:5000/api/productsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[ { "id": 1, "name": "Mixer Grinder", "price": 2499 }, { "id": 2, "name": "Steel Bottle", "price": 399 }]- [ApiController] turns on API features (body binding, ProblemDetails for errors).
- ControllerBase is the right base class for an API (Controller adds view support).
- GetAll maps every product to a ProductDto and returns 200 with a JSON array.
45.5 GET by id: 200 or 404
C#
[HttpGet("{id:int}")]public ActionResult<ProductDto> GetById(int id){ var product = store.Find(id); if (product is null) return NotFound(); return product.ToDto();}Output
$ curl -i localhost:5000/api/products/1HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "id": 1, "name": "Mixer Grinder", "price": 2499 } $ curl -i localhost:5000/api/products/99HTTP/1.1 404 Not FoundContent-Type: application/problem+json; charset=utf-8{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5", "title": "Not Found", "status": 404}- ActionResult<ProductDto> lets one method return either data or a result like NotFound().
- Returning the DTO directly is wrapped in 200 OK by the framework.
- NotFound() gives 404 with a ProblemDetails body (because of [ApiController]).
45.6 POST: 201 + Location
C#
[HttpPost]public ActionResult<ProductDto> Create( CreateProductRequest request){ var product = store.Add( request.Name, request.Price); var dto = product.ToDto(); return CreatedAtAction(nameof(GetById), new { id = dto.Id }, dto);}Output
$ curl -i localhost:5000/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Pressure Cooker","price":1899}'HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: http://localhost:5000/api/products/3{ "id": 3, "name": "Pressure Cooker", "price": 1899 }- CreateProductRequest has only Name and Price; with [ApiController] it comes from the JSON body.
- CreatedAtAction(nameof(GetById), new { id }, dto) sends 201 Created and a Location header with the new product URL.
45.7 PUT and DELETE: 204
C#
[HttpPut("{id:int}")]public IActionResult Update(int id, UpdateProductRequest request){ var updated = store.Update(id, request.Name, request.Price); return updated ? NoContent() : NotFound();} [HttpDelete("{id:int}")]public IActionResult Delete(int id){ var removed = store.Remove(id); return removed ? NoContent() : NotFound();}Output
$ curl -i -X PUT localhost:5000/api/products/3 \ -H "Content-Type: application/json" \ -d '{"name":"Pressure Cooker 5L","price":2199}'HTTP/1.1 204 No ContentServer: Kestrel $ curl -i -X DELETE localhost:5000/api/products/3HTTP/1.1 204 No ContentServer: Kestrel- PUT takes the id from the URL and the new data from the body.
- NoContent() = 204: work done, no body. Missing product = NotFound().
- IActionResult is used when no data is returned; ActionResult<T> when data is returned.
- Step 1
1.Routing: URL + HTTP method -> action
- Step 2
2.Model binding: id from route, body -> parameters
- Step 3
3.Action runs and returns an ActionResult
- Step 4
4.Framework writes status + headers + JSON body
The controller returns a result, the framework writes it
45.8 Checkpoint: DELETE again?
Output
# same DELETE again$ curl -i -X DELETE localhost:5000/api/products/3HTTP/1.1 404 Not FoundContent-Type: application/problem+json; charset=utf-8{ "title": "Not Found", "status": 404, ... }- Product 3 no longer exists, so Remove returns false and the action returns 404.
- Server state is the same both times, so DELETE is still idempotent; the status only says nothing was deleted this time.
45.9 Status codes for a REST controller
| Action | Success | Helper | Failure |
|---|---|---|---|
| GET list | 200 OK | return data / Ok() | - |
| GET by id | 200 OK | return dto | 404 NotFound() |
| POST | 201 Created + Location | CreatedAtAction() | 400 (invalid body) |
| PUT | 204 No Content | NoContent() | 404 NotFound() |
| DELETE | 204 No Content | NoContent() | 404 NotFound() |
45.10 Return a DTO, not the entity
C#
// Wrong: entity returned directly (costPrice leak + overposting)[HttpGet("{id}")]public Product? GetById(int id) => store.Find(id);// { "id": 1, "name": "Mixer Grinder",// "price": 2499, "costPrice": 1800 }C#
public record ProductDto( int Id, string Name, decimal Price); public record CreateProductRequest( string Name, decimal Price); // GET /api/products/1// { "id": 1, "name": "Mixer Grinder",// "price": 2499 }- Returning the entity leaks internal fields (costPrice) to customers.
- Accepting the entity allows overposting: a client can send costPrice in the body and overwrite it.
- ProductDto has only what the client needs; CreateProductRequest accepts only what a client may send, so internal changes don't break clients.
45.11 Content negotiation: the Accept header
C#
builder.Services.AddControllers(options =>{ options.ReturnHttpNotAcceptable = true;});Output
# default AddControllers$ curl -i localhost:5000/api/products/1 \ -H "Accept: application/xml"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8 # ReturnHttpNotAcceptable = true$ curl -i localhost:5000/api/products/1 \ -H "Accept: application/xml"HTTP/1.1 406 Not AcceptableContent-Length: 0- The client asks for a format with the Accept header.
- By default only a JSON formatter exists, so even Accept: application/xml gets JSON.
- ReturnHttpNotAcceptable = true gives 406 Not Acceptable for unsupported formats.
45.12 Common mistakes
- Returning a plain type (Product?) from actions: 204 instead of 404, 200 instead of 201.
- Exposing entities instead of DTO records.
- Using Controller (for views) instead of ControllerBase for a pure API.
- Myth: controllers are outdated. Both controllers and Minimal APIs are fully supported.
- Fat controllers: business logic belongs in services, the controller stays thin.
45.13 Interview tips
- I inherit from ControllerBase and use [ApiController] with attribute routing.
- Actions return ActionResult<T>, so the status code is always correct.
- Create uses CreatedAtAction to send 201 with a Location header; missing resource = 404; PUT/DELETE = 204.
- I expose DTOs instead of entities so sensitive fields never leak and overposting is not possible.