Controllers
Learn how to write controller actions, return different response types, and use ActionResult in ASP.NET Core.
What is a Controller?
A controller is a class that handles incoming HTTP requests, typically inheriting from `ControllerBase` (for APIs) or `Controller` (for MVC apps with views).
Writing Actions
Each public method in a controller — called an "action" — handles one specific kind of request.
[ApiController][Route("api/[controller]")]public class TasksController : ControllerBase{ private static List<string> tasks = new List<string> { "Buy milk", "Write code" };
[HttpGet] public IActionResult GetAll() => Ok(tasks);}ActionResult Types
| Method | HTTP Status | Use Case |
|---|---|---|
| Ok(data) | 200 | Successful response with data |
| NotFound() | 404 | Requested resource doesn't exist |
| BadRequest(errors) | 400 | Invalid input from the client |
| CreatedAtAction(...) | 201 | A new resource was successfully created |
| NoContent() | 204 | Success, nothing to return (e.g. after delete) |
A Complete Controller
[ApiController][Route("api/[controller]")]public class TasksController : ControllerBase{ private static List<string> tasks = new List<string> { "Buy milk" };
[HttpGet] public IActionResult GetAll() => Ok(tasks);
[HttpGet("{id}")] public IActionResult GetById(int id) { if (id < 0 || id >= tasks.Count) return NotFound(); return Ok(tasks[id]); }
[HttpPost] public IActionResult Create([FromBody] string task) { tasks.Add(task); return CreatedAtAction(nameof(GetAll), null, task); }}FAQs
IActionResult lets one action return different response types (Ok, NotFound, BadRequest) depending on the situation, rather than always returning the same shape.
Summary
- Controllers handle incoming requests and coordinate a response.
- ActionResult helpers (Ok, NotFound, BadRequest) map directly to HTTP status codes.
- A well-designed controller keeps each action focused on one responsibility.