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
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
Examples
public IActionResult Details(int id)
{
if (id <= 0)
return BadRequest("Invalid ID");
var item = repo.Find(id);
if (item == null)
return NotFound();
return View(item);
}
This action might return:
BadRequestif the ID is invalidNotFoundif the item isn't foundViewif the item exists
Another example:
public IActionResult Download(int id)
{
var file = fileService.GetFile(id);
if (file == null)
return NotFound();
return File(file.Bytes, file.ContentType, file.FileName);
}
This action returns either a file download or a 404 "Not Found" error depending on the logic.
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 (has data) | Ok() |
| Success (no content) | NoContent() |
| Created (new resource) | Created() |
| Unauthorized (auth required) | Unauthorized() |
| Forbidden (no permission) | StatusCode(403) |
| Server error | StatusCode(500) |
| Navigate elsewhere | Redirect*() |