Controller 中的公共方法即 Action,但並非所有公共方法都是 Action。本文詳細列舉 Action 的限制條件,並通過自定義 ActionResult 揭示 View 的真實本質。
public 實例方法static、abstract、建構函式、屬性存取器Controller 基類方法(如 ToString)ref/out 參數[NonAction] 屬性[NonAction]
public string DisplayString() { return "this is a demo string!"; } // 不會被當作 Action
最常見的 return View(); 實際返回 ViewResult(繼承 ActionResult)。MVC 無實體 .aspx/.cshtml 檔案對應 URL,所有請求最終映射至 Action,由 ActionResult 決定響應形式。
繼承 ActionResult 並覆寫 ExecuteResult:
public class RssActionResult : ActionResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = "application/rss+xml";
var rss = new Rss();
rss.CreateSampleRss(response); // 寫入 RSS XML
}
}
// Controller 中使用
public ActionResult RssFeed() { return new RssActionResult(); }
ActionResult 實例ControllerActionInvoker 調用 ExecuteResult(ControllerContext)| 類型 | 用途 | 典型場景 |
|---|---|---|
| ViewResult | 渲染視圖模板 | 返回 HTML 頁面 |
| PartialViewResult | 渲染部分視圖 | AJAX 區塊更新 |
| JsonResult | 序列化物件為 JSON | Web API、AJAX 回傳 |
| RedirectResult | HTTP 302 重導向 | POST 後導向 GET |
| FileResult | 輸出二進位檔案 | 下載 Excel、PDF、圖片 |
| ContentResult | 輸出純文字/HTML/JS | 動態生成 JS/CSS |
| EmptyResult | 無內容響應 | AJAX 只需狀態碼 |
將「做什麼」與「怎麼呈現」分離:Action 只負責準備資料並選擇 ActionResult,具體輸出邏輯封裝在衍生類中。這符合單一職責原則,也方便單元測試(直接斷言返回的 Result 類型與屬性)。