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

ASP.NET MVC 控制器核心機制:路由對應、ActionResult 與視圖渲染流程詳解

     編輯:ASP.NET 基礎

ASP.NET MVC 控制器核心機制解析


深入理解 MVC 控制器架構:URL 路由對應原理、Action 方法設計、ActionResult 類型與視圖渲染流程。


Controllers 資料夾與命名慣例

  • 所有控制器類別檔名必須以 Controller 結尾
  • 專案範本預設產生:
HomeController.cs    // 首頁、關於頁
AccountController.cs // 登入、註冊、帳號管理

Controllers 資料夾結構

MVC 路由對應機制

傳統 Web vs MVC 對應差異

架構URL 對應方式範例
傳統 WebURL 直接對應實體檔案/index.php → 根目錄 index.php
MVCURL 對應到 Controller Action 方法/Home/About → HomeController.About()

預設路由規則 (RouteConfig.cs)

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

URL 解析範例

URLControllerActionid 參數
/HomeIndex(預設)
/Home/AboutHomeAbout(預設)
/Movies/Edit/5MoviesEdit5
/Account/LogOnAccountLogOn(預設)

HomeController 實作範例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        // GET: /Home/About
        public ActionResult About()
        {
            return View();
        }
    }
}

關鍵觀念

  • 繼承 Controller 基類別
  • Action 方法回傳 ActionResult(或衍生類型)
  • return View() 依慣例尋找 Views/ControllerName/ActionName.cshtml

ActionResult 類型完整圖譜

結果類型用途Helper 方法
ViewResult渲染視圖View()
PartialViewResult渲染部分視圖PartialView()
RedirectResult重導向至 URLRedirect()
RedirectToRouteResult重導向至路由RedirectToAction()
JsonResult回傳 JSON 資料Json()
ContentResult回傳純文字/HTMLContent()
FileResult回傳檔案下載File()
EmptyResult無回傳內容new EmptyResult()
HttpStatusCodeResult指定 HTTP 狀態碼new HttpStatusCodeResult(404)

控制器與視圖對應關係

Views 資料夾結構:

Views/
└── Home/
    ├── Index.cshtml   ← 對應 HomeController.Index()
    └── About.cshtml   ← 對應 HomeController.About()

視圖搜尋順序

  1. Views/ControllerName/ActionName.cshtml
  2. Views/ControllerName/ActionName.vbhtml
  3. Views/Shared/ActionName.cshtml
  4. Views/Shared/ActionName.vbhtml

進階控制器模式

傳遞資料給視圖

public ActionResult Details(int id)
{
    var movie = db.Movies.Find(id);
    if (movie == null) return HttpNotFound();
    
    // 強型別模型
    return View(movie);
    
    // 或使用 ViewBag/ViewData
    ViewBag.Message = "電影詳情";
    return View(movie);
}

模型繫結與參數接收

// 簡單類型自動繫結
public ActionResult Edit(int id, string title)

// 複雜類型自動繫結表單欄位
[HttpPost]
public ActionResult Edit(MovieDB model)
{
    if (ModelState.IsValid) { ... }
    return View(model);
}

Action 過濾器

[Authorize]           // 需驗證
[HttpPost]            // 僅接受 POST
[ValidateAntiForgeryToken] // CSRF 防護
[OutputCache(Duration=60)] // 輸出快取
public ActionResult SecureAction() { ... }

最佳實務建議

  1. 單一職責:每個 Action 專注單一業務邏輯
  2. 薄控制器:業務邏輯移至 Service Layer,控制器只負責協調
  3. 非同步 Action:I/O 密集操作使用 async Task<ActionResult>
  4. 錯誤處理:統一使用 HandleErrorAttribute 或自訂例外過濾器
  5. 測試性:依賴注入 Service,便於單元測試
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved