MVC 控制器
详解 ASP.NET MVC 控制器目录与 *Controller 命名规范、URL 到控制器操作方法的路由分发原理、HomeController 的 ActionResult/View() 机制以及现代 ASP.NET Core MVC 演进。
学完这一章,你能够
- 详解 ASP.NET MVC 控制器目录与 *Controller 命名规范、URL 到控制器操作方法的路由分发原理、HomeController 的 ActionResult/View() 机制以及现代 ASP.NET Core MVC 演进。
Controllers 目录约定与 URL 到控制器方法路由
进入 MvcDemo 实战第 4 部分:添加与编写控制器。所有控制器类都存放在 `Controllers` 文件夹下,并严格遵循“类名与文件名必须以 `Controller` 结尾”的框架约定。新建项目时模板已自动生成 `HomeController.cs`(负责站点首页与关于页)和 `AccountController.cs`(负责用户登录与注册)。
传统 Web 服务器通常把请求 URL 直接映射到磁盘物理文件,例如访问 `https://example.com/index.php` 会直接定位站点根目录下的 `index.php` 文件。ASP.NET MVC 采用截然不同的路由分发机制:框架依据路由模板(默认 `{controller}/{action}/{id}`)将 URL 映射到控制器类中的具体公共方法(称为 Action 操作方法)。控制器统筹处理进入的 HTTP 请求、校验输入、调用模型保存数据并向客户端返回视图或数据响应。
HomeController 实现与控制器-视图映射
在 `MvcDemo.Controllers` 命名空间下,`HomeController` 继承自 `System.Web.Mvc.Controller` 基类,并定义了两个公开操作方法 `Index()` 与 `About()`,二者均声明返回 `ActionResult` 并调用 `return View();` 交由视图引擎渲染 HTML 页面。
调用无参 `return View()` 时,MVC 视图引擎按约定自动查找与控制器和操作同名的模板文件:`HomeController.Index()` 对应 `Views/Home/Index.cshtml`,`HomeController.About()` 对应 `Views/Home/About.cshtml`。在现代 ASP.NET Core MVC 中,控制器位于 `Microsoft.AspNetCore.Mvc` 命名空间,操作方法普遍返回接口类型 `IActionResult`(异步操作返回 `Task<IActionResult>`),并可结合 `[Route]`、`[HttpGet]`/`[HttpPost]` 特性路由与 `Program.cs` 中的 `app.MapControllerRoute(...)` 灵活控制路由规则。
离线校验 MVC 路由模板解析、Controller 后缀发现约定与 HomeController 视图映射
"""Offline ASP.NET MVC controllers & routing verification lab for Chapter 30 (mvc-controllers)."""
import json
VERSION = "CPython 3.12.14 offline ASP.NET MVC controller routing semantic verifier (IIS/ASP.NET host absent)"
def route_url(path, defaults=("Home", "Index")):
parts = [p for p in path.strip("/").split("/") if p]
controller = parts[0] if len(parts) >= 1 else defaults[0]
action = parts[1] if len(parts) >= 2 else defaults[1]
route_id = parts[2] if len(parts) >= 3 else None
return {"controller": controller, "action": action, "id": route_id}
def case_mvc_route_template_dispatch():
expected = {
"root": {"controller": "Home", "action": "Index", "id": None},
"about": {"controller": "Home", "action": "About", "id": None},
"edit_movie": {"controller": "Movies", "action": "Edit", "id": "3"},
}
actual = {
"root": route_url("/"),
"about": route_url("/Home/About"),
"edit_movie": route_url("/Movies/Edit/3"),
}
return {
"name": "mvc_route_template_dispatch",
"summary": "验证默认路由模板 {controller}/{action}/{id} 对根路径、/Home/About 与 /Movies/Edit/3 的解析分发",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_controller_suffix_convention_validation():
candidates = ["HomeController", "AccountController", "MoviesController", "HelperService"]
discovered = {c[: -len("Controller")]: c for c in candidates if c.endswith("Controller")}
expected = {
"discovered_count": 3,
"home_class": "HomeController",
"non_controller_ignored": True,
}
actual = {
"discovered_count": len(discovered),
"home_class": discovered.get("Home"),
"non_controller_ignored": "HelperService" not in discovered.values(),
}
return {
"name": "controller_suffix_convention_validation",
"summary": "验证控制器类名必须以 Controller 结尾的框架发现约定,过滤非控制器类",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_home_controller_actions_and_view_resolution():
actions = {
"Home": {
"Index": lambda: {"type": "ViewResult", "view_path": "Views/Home/Index.cshtml"},
"About": lambda: {"type": "ViewResult", "view_path": "Views/Home/About.cshtml"},
}
}
r1 = route_url("/")
r2 = route_url("/Home/About")
res1 = actions[r1["controller"]][r1["action"]]()
res2 = actions[r2["controller"]][r2["action"]]()
expected = {
"index_view": "Views/Home/Index.cshtml",
"about_view": "Views/Home/About.cshtml",
"both_view_result": True,
}
actual = {
"index_view": res1["view_path"],
"about_view": res2["view_path"],
"both_view_result": res1["type"] == "ViewResult" and res2["type"] == "ViewResult",
}
return {
"name": "home_controller_actions_and_view_resolution",
"summary": "验证 HomeController.Index() 与 HomeController.About() 返回 ActionResult/View() 到对应 .cshtml 的映射",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_mapping_vs_mvc_routing():
traditional_url = "https://example.com/index.php"
mvc_url = "https://example.com/Home/About"
expected = {
"traditional_maps_to": "disk_file:index.php",
"mvc_maps_to": "method:HomeController.About()",
"decouples_url_from_filesystem": True,
}
actual = {
"traditional_maps_to": "disk_file:" + traditional_url.rsplit("/", 1)[-1],
"mvc_maps_to": "method:" + route_url("/Home/About")["controller"] + "Controller." + route_url("/Home/About")["action"] + "()",
"decouples_url_from_filesystem": not mvc_url.endswith(".cshtml"),
}
return {
"name": "file_mapping_vs_mvc_routing",
"summary": "对比传统物理文件 URL 映射(index.php)与 MVC 控制器方法路由映射的架构差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_mvc_route_template_dispatch(),
case_controller_suffix_convention_validation(),
case_home_controller_actions_and_view_resolution(),
case_file_mapping_vs_mvc_routing(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 离线验证器确认 {controller}/{action}/{id} 路由解析、非 Controller 后缀类过滤、HomeController.Index/About 映射至对应 .cshtml 及文件映射与路由映射对比全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
当前源码 SHA256:1a2f667a7bd0b1db995129c6e86c738f45d57062f2f709b9c4b815466d2d8291
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
ZIP SHA256:6bff6cc42e711c3b840955b993e40c84448e97539cb01465d1282ced8a87ef81
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在默认路由 `{controller=Home}/{action=Index}/{id?}` 下,访问 `/Movies/Edit/3` 会被分发到哪个控制器类的哪个方法?
展开参考解答
会分发到 `MoviesController` 类的 `Edit` 操作方法,并将路由参数 `id` 绑定为 `3`(例如 `public IActionResult Edit(int id)`)。