Skip to main content

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) or ControllerBase (API)
  • Lives in the Controllers folder (by convention)

2. Action Methods

Action methods are:

  • public methods 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:

  • BadRequest if the ID is invalid
  • NotFound if the item isn't found
  • View if 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)

NeedUse
Plain text / HTMLContent()
API dataJson()
File downloadFile()
Validation errorBadRequest()
Missing resourceNotFound()
Success (has data)Ok()
Success (no content)NoContent()
Created (new resource)Created()
Unauthorized (auth required)Unauthorized()
Forbidden (no permission)StatusCode(403)
Server errorStatusCode(500)
Navigate elsewhereRedirect*()