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

ASP.NET MVC ActionResult 本質解析:EmptyResult 與 ContentResult 基礎回應機制

     編輯:關於ASP.NET

ActionResult 基礎架構

Controller 可直接操作 Response、HttpContext、ControllerContext 回應,但慣例透過 ActionResult 封裝:

public abstract class ActionResult
{
    public abstract void ExecuteResult(ControllerContext context);
}

ActionInvoker 執行 Action 後,若回傳 ActionResult 則呼叫其 ExecuteResult。

EmptyResult:空回應適配器

public class EmptyResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context) { }
}

設計意義

  • Action 回傳 void 或 null 時,ActionInvoker 自動建立 EmptyResult。
  • 統一管道流程:Action 執行 → 產生 ActionResult → 執行 ActionResult,無需特判無回傳值情況。
  • 適配器模式:將「無結果」適配為統一介面。

ContentResult:字串內容回應

public class ContentResult : ActionResult
{
    public string Content { get; set; }
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = ContentType ?? "text/plain";
        if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
        response.Write(Content ?? String.Empty);
    }
}

// Controller 便利方法
protected ContentResult Content(string content);
protected ContentResult Content(string content, string contentType);
protected virtual ContentResult Content(string content, string contentType, Encoding contentEncoding);

常見用法

  • 純文字:return Content("Hello"); → text/plain
  • HTML:return Content("<b>Hello</b>", "text/html");
  • JSON (舊版):return Content(jsonString, "application/json");
  • JavaScript:return Content(script, "application/x-javascript");
  • XML:return Content(xmlString, "application/xml", Encoding.UTF8);

總結

EmptyResult 為無回傳值適配器,ContentResult 為最基礎的字串內容回應,支援完整編碼與媒體類型控制。所有具體 ActionResult 均遵循「建構資料 → ExecuteResult 寫入 Response」模式,理解此核心有助於自訂 Result 類別。

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