LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 5120 min read

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

MethodHTTP StatusUse Case
Ok(data)200Successful response with data
NotFound()404Requested resource doesn't exist
BadRequest(errors)400Invalid input from the client
CreatedAtAction(...)201A new resource was successfully created
NoContent()204Success, 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.
Next Lesson →

Views & Razor Syntax