首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC Action 與 View 深度解析:自定義 ActionResult 與視圖本質

     編輯:關於ASP.NET

Controller 中的公共方法即 Action,但並非所有公共方法都是 Action。本文詳細列舉 Action 的限制條件,並通過自定義 ActionResult 揭示 View 的真實本質。

合法 Action 的六大條件

  • 必須是 public 實例方法
  • 不能是 static、abstract、建構函式、屬性存取器
  • 不能是 Controller 基類方法(如 ToString)
  • 不能包含 ref/out 參數
  • 不能是擴充方法
  • 未標記 [NonAction] 屬性
[NonAction]
public string DisplayString() { return "this is a demo string!"; } // 不會被當作 Action

View 的本質:ActionResult 的一種

最常見的 return View(); 實際返回 ViewResult(繼承 ActionResult)。MVC 無實體 .aspx/.cshtml 檔案對應 URL,所有請求最終映射至 Action,由 ActionResult 決定響應形式。

自定義 ActionResult 實戰:輸出 RSS

繼承 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 執行流程

  1. Action 方法返回 ActionResult 實例
  2. ControllerActionInvoker 調用 ExecuteResult(ControllerContext)
  3. 衍生類在該方法中:設定 Header、寫入 Response Stream、觸發視圖引擎渲染等

內建 ActionResult 家族

類型用途典型場景
ViewResult渲染視圖模板返回 HTML 頁面
PartialViewResult渲染部分視圖AJAX 區塊更新
JsonResult序列化物件為 JSONWeb API、AJAX 回傳
RedirectResultHTTP 302 重導向POST 後導向 GET
FileResult輸出二進位檔案下載 Excel、PDF、圖片
ContentResult輸出純文字/HTML/JS動態生成 JS/CSS
EmptyResult無內容響應AJAX 只需狀態碼

設計啟示

將「做什麼」與「怎麼呈現」分離:Action 只負責準備資料並選擇 ActionResult,具體輸出邏輯封裝在衍生類中。這符合單一職責原則,也方便單元測試(直接斷言返回的 Result 類型與屬性)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved