跳到主要内容

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 (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)

NeedUse
Plain text / HTMLContent()
API dataJson()
File downloadFile()
Validation errorBadRequest()
Missing resourceNotFound()
SuccessOk()
Navigate elsewhereRedirect*()

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."