Controllers & Action Methods
1. What is a Controller?
A controller is a class that:
- Handles HTTP requests
- Calls the data/service layer
- Returns a response (view, JSON, file, status code, redirect, etc.)
Think: request coordinator
Rules
- Class name ends with
Controller - Inherits from
Controller(MVC) orControllerBase(API) - Lives in the
Controllersfolder (by convention)
2. Action Methods
Action methods are:
publicmethods inside controllers- Each handles one request
- Selected via routing
They usually return IActionResult.
public IActionResult Index()
{
return Content("Hello");
}
3. Attribute Routing (Most Common)
Routes are defined directly on controllers/actions.
[Route("home")]
public class HomeController : Controller
{
[HttpGet("")]
public IActionResult Index() => Content("Home");
[HttpGet("about")]
public IActionResult About() => Content("About");
}
Enable controllers:
builder.Services.AddControllers();
app.MapControllers();
4. IActionResult (Key Concept)
IActionResult lets an action return different responses based on logic.
One action → many possible results
5. Common Action Results (Know These)
ContentResult (raw text / HTML)
return Content("<h1>Hello</h1>", "text/html");
JsonResult (JSON response)
return Json(new { id = 1, name = "Book" });
(Content-Type auto = application/json)
File Results
return File("/sample.pdf", "application/pdf"); // from wwwroot
return PhysicalFile(@"C:\file.pdf", "application/pdf");
return File(bytes, "application/pdf"); // in-memory
Status Code Results
return Ok(); // 200
return BadRequest("Invalid"); // 400
return NotFound(); // 404
return Unauthorized(); // 401
return StatusCode(403); // custom
Redirect Results
return Redirect("/home"); // URL
return RedirectToAction("Index", "Home"); // action
return LocalRedirect("/products/10"); // local only
6. Typical Action with Validation
[HttpGet("book")]
public IActionResult GetBook(int id)
{
if (id <= 0)
return BadRequest("Invalid id");
if (id > 1000)
return NotFound();
return File("/sample.pdf", "application/pdf");
}
One action, multiple IActionResults
7. When to Use What (Mental Map)
| Need | Use |
|---|---|
| Plain text / HTML | Content() |
| API data | Json() |
| File download | File() |
| Validation error | BadRequest() |
| Missing resource | NotFound() |
| Success | Ok() |
| Navigate elsewhere | Redirect*() |
8. Interview One-Liner 🎯
"Controllers group related actions that handle HTTP requests. Each action returns an
IActionResult, which allows flexible responses like JSON, files, redirects, or status codes. Routing decides which action runs."