Controller 可直接操作 Response、HttpContext、ControllerContext 回應,但慣例透過 ActionResult 封裝:
public abstract class ActionResult
{
public abstract void ExecuteResult(ControllerContext context);
}
ActionInvoker 執行 Action 後,若回傳 ActionResult 則呼叫其 ExecuteResult。
public class EmptyResult : ActionResult
{
public override void ExecuteResult(ControllerContext context) { }
}
void 或 null 時,ActionInvoker 自動建立 EmptyResult。Action 執行 → 產生 ActionResult → 執行 ActionResult,無需特判無回傳值情況。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/plainreturn Content("<b>Hello</b>", "text/html");return Content(jsonString, "application/json");return Content(script, "application/x-javascript");return Content(xmlString, "application/xml", Encoding.UTF8);EmptyResult 為無回傳值適配器,ContentResult 為最基礎的字串內容回應,支援完整編碼與媒體類型控制。所有具體 ActionResult 均遵循「建構資料 → ExecuteResult 寫入 Response」模式,理解此核心有助於自訂 Result 類別。