ASP.NET Core MVC Intermediate

Web API controllers

An API controller returns data, usually JSON, for JavaScript front ends, mobile apps or other services. This lesson builds a REST API for products with [ApiController], correct status codes, ProblemDetails errors and OpenAPI documentation.

A POST to the API
  1. StartClient sends JSONPOST /api/products
  2. Step 2[ApiController] validates400 with details if invalid
  3. Step 3Action savesEF Core inserts the product
  4. Step 4201 CreatedLocation header points to GET /api/products/42
  5. EndClient reads DTOId, Name, Price

What [ApiController] adds

  • Automatic 400 responses with validation details when the model is invalid, so no ModelState checks are needed.
  • Binding source rules: complex types come from the JSON body, simple types from the route or query.
  • Error responses in the standard ProblemDetails format.
  • Attribute routing is required, which keeps API URLs explicit.
  • API controllers inherit ControllerBase, not Controller, because they have no views.

A products API

C#
[ApiController]
[Route("api/products")]
public class ProductsApiController(ShopContext db) : ControllerBase
{
    [HttpGet]
    public async Task<IEnumerable<ProductDto>> List(int page = 1, CancellationToken ct = default) =>
        await db.Products.OrderBy(p => p.Id).Skip((page - 1) * 20).Take(20)
            .Select(p => new ProductDto(p.Id, p.Name, p.Price)).ToListAsync(ct);

    [HttpGet("{id:int}")]
    public async Task<ActionResult<ProductDto>> Get(int id, CancellationToken ct)
    {
        var p = await db.Products.FindAsync([id], ct);
        return p is null ? NotFound() : new ProductDto(p.Id, p.Name, p.Price);
    }

    [HttpPost]
    public async Task<ActionResult<ProductDto>> Create(CreateProduct input, CancellationToken ct)
    {
        var p = new Product { Name = input.Name, Price = input.Price };
        db.Products.Add(p);
        await db.SaveChangesAsync(ct);
        return CreatedAtAction(nameof(Get), new { id = p.Id }, new ProductDto(p.Id, p.Name, p.Price));
    }

    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id, CancellationToken ct) =>
        await db.Products.Where(p => p.Id == id).ExecuteDeleteAsync(ct) == 0 ? NotFound() : NoContent();
}

public record ProductDto(int Id, string Name, decimal Price);
public record CreateProduct([Required, StringLength(200)] string Name, [Range(0, 1_000_000)] decimal Price);

Status codes and documentation

  • 200 OK with data, 201 Created with a Location header after POST, 204 No Content after DELETE.
  • 400 for invalid input, 401 when not signed in, 403 when not allowed, 404 when missing, 409 for conflicts.
  • builder.Services.AddProblemDetails() makes unhandled errors return ProblemDetails JSON too.
  • In .NET 9 and later, AddOpenApi() and MapOpenApi() publish an OpenAPI document; tools such as Scalar or Swagger UI show it.

Interview question

What does the [ApiController] attribute do?

It turns on API-specific behaviour: invalid models automatically return a 400 response with validation details, complex parameters are bound from the request body by default, error status codes produce ProblemDetails responses, and attribute routing becomes required. This removes boilerplate such as checking ModelState in every action.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.