Controller là gì?
Controller được dùng để định nghĩa và nhóm một tập hợp các actions. Một action (hay action method) là method trên controller dùng để xử lý requests. Controllers nhóm các actions tương tự lại với nhau, cho phép áp dụng các quy tắc chung như routing, caching và authorization cho toàn bộ nhóm. Requests được map đến actions thông qua routing. Controllers được khởi tạo và hủy trên mỗi request.Quy ước đặt tên Controller
Theo quy ước, controller classes:- Nằm trong thư mục
Controllersở root của project - Kế thừa từ
Microsoft.AspNetCore.Mvc.Controller
| Điều kiện | Ví dụ |
|---|---|
Tên class có suffix "Controller" | ProductsController |
Kế thừa class có suffix "Controller" | Kế thừa BaseController |
Class được decorate với [Controller] | @[Controller] |
Controller và mô hình MVC
Trong mô hình MVC, controller chịu trách nhiệm:- Xử lý request ban đầu — đảm bảo request data hợp lệ
- Instantiate model — tạo đối tượng model
- Chọn kết quả trả về — View hoặc API response
Lưu ý: Controller là một abstraction ở mức UI. Trong ứng dụng được thiết kế tốt, controller không trực tiếp thực hiện data access hay business logic. Thay vào đó, controller delegates đến các services xử lý các trách nhiệm này.
Dependency Injection trong Controller
Controllers nên tuân theo Explicit Dependencies Principle.| Loại injection | Khi nào dùng |
|---|---|
| Constructor Injection | Nhiều action methods cần cùng service |
| Action Injection | Chỉ một action method cần service đó |
Constructor Injection
Action Injection
Action Methods
Định nghĩa Action
Tất cả public methods trên controller đều là actions, trừ method có attribute[NonAction].
Action Parameters và Model Binding
Parameters trên actions được bind từ request data và validated bằng model binding. Model validation xảy ra cho tất cả model-bound parameters. PropertyModelState.IsValid cho biết binding và validation có thành công không.
Action Results
Actions có thể trả về bất kỳ type nào, nhưng thường trả vềIActionResult (hoặc Task<IActionResult> cho async methods).
Controller Helper Methods
Controllers kế thừa từController có quyền truy cập 3 nhóm helper methods:
1. Trả về Response Body rỗng
Không cóContent-Type HTTP header vì response body không có nội dung.
HTTP Status Code
| Method | HTTP Status | Mô tả |
|---|---|---|
BadRequest() | 400 | Bad request |
NotFound() | 404 | Không tìm thấy |
Ok() | 200 | Thành công |
NoContent() | 204 | Không có nội dung |
StatusCode(500) | 500 | Internal server error |
Redirect
| Method | Mô tả |
|---|---|
Redirect(url) | Redirect đến URL |
LocalRedirect(url) | Redirect đến local URL, ngăn open redirect attack |
RedirectToAction(action) | Redirect đến action |
RedirectToRoute(route) | Redirect đến route cụ thể |
2. Trả về Response Body có predefined Content-Type
View
Formatted Response
| Method | Content-Type | Mô tả |
|---|---|---|
Json(object) | application/json | Serialize object sang JSON |
File(path, type) | Tùy chỉnh | Trả về file |
PhysicalFile(path, type) | Tùy chỉnh | Trả về file từ filesystem |
Content(text, type) | Tùy chỉnh | Trả về string với content type |
3. Content Negotiation
Content Negotiation xảy ra khi action trả vềObjectResult hoặc non-IActionResult. Các method này tự động chọn format (JSON/XML) dựa trên Accept header của client.
Cross-Cutting Concerns
Cross-cutting concerns là các phần workflow được chia sẻ giữa nhiều parts của ứng dụng, như authentication, logging, error handling.Ví dụ: Cross-cutting concerns thường gặp
| Cross-cutting concern | Giải pháp |
|---|---|
| Authentication | [Authorize], [AllowAnonymous] |
| Authorization | Policy-based authorization |
| Error Handling | [ExceptionHandler] filter, middleware |
| Response Caching | [ResponseCache] filter |
| Logging | Action filter hoặc middleware |
| Localization | Action filter |