蓝色天空.知识 · 实践 · 创造
我的收藏
ASP.NET 教程目录 55章
ASP.NET / LEARN BY DOING

MVC 布局

详解 ASP.NET MVC 共享布局页 _Layout.cshtml 的 @ViewBag.Title、@RenderBody()、@Url.Content()、@Html.ActionLink() 协作机制,Site.css 样式分组与 _ViewStart.cshtml 自动布局注入,并对比 ASP.NET Core Tag Helpers。

学完这一章,你能够

  • 详解 ASP.NET MVC 共享布局页 _Layout.cshtml 的 @ViewBag.Title、@RenderBody()、@Url.Content()、@Html.ActionLink() 协作机制,Site.css 样式分组与 _ViewStart.cshtml 自动布局注入,并对比 ASP.NET Core Tag Helpers。

共享布局页 _Layout.cshtml 与核心 Razor / HTML 帮助器

在 MvcDemo 实战第 3 部分中,我们为整站统一外观与导航结构。位于 `Views/Shared/_Layout.cshtml` 的布局文件定义了所有页面共享的 HTML5 外壳(`<!DOCTYPE html>`、`<head>` 资源引用、顶部菜单 `<ul id="menu">` 与 `<section id="main">` 主容器),使每个具体页面无需重复编写页头与页脚。

布局页中借助内置 HTML 帮助器与 URL 帮助器动态生成可靠输出:`@Url.Content("~/Content/Site.css")` 将以波浪号 `~/` 开头的虚拟应用根路径解析为实际可访问的站点 URL(即使应用部署在虚拟子目录下也能正确定位静态文件);`@Html.ActionLink("Home", "Index", "Home")`、`@Html.ActionLink("Movies", "Index", "Movies")` 与 `@Html.ActionLink("About", "About", "Home")` 则依据路由表生成指向对应控制器操作的 `<a>` 导航链接(更多帮助器将在后文详述)。

在 `_Layout.cshtml` 中嵌入的 Razor C# 表达式承担两个关键占位职责:`@ViewBag.Title` 在 `<title>` 中输出当前具体视图设置的标题文本,并且 Razor 会自动对其执行 HTML 编码以防范 XSS 脚本注入;`@RenderBody()` 则作为主体插槽,在运行时将具体视图(如 `Index.cshtml`)的 HTML 正文渲染到 `<section id="main">` 中(可结合前文 Razor C#/VB 语法章节复习细节)。在现代 ASP.NET Core MVC 中,静态路径引用可直接使用 `~/css/site.css` 搭配 `asp-append-version="true"` 缓存破坏,导航链接推荐使用 Tag Helpers(`<a asp-controller="Movies" asp-action="Index">Movies</a>`),并通过 `@RenderSection("Scripts", required: false)` 灵活注入页面级脚本。

全局样式表 Site.css 与 _ViewStart.cshtml 默认布局注入

应用程序的全局样式定义在 `Content/Site.css` 中,按职责清晰划分为四组规则:基础排版与主容器(`body`、`h1`、`#main`、`a`)、水平标签式导航菜单(`ul#menu`、`ul#menu li`、`ul#menu li a` 与 `:hover` 圆角高亮)、表单控件布局(`fieldset`、`label`、`input[type="text"]`、`input[type="password"]`、`input[type="submit"]`)以及数据网格表格样式(`table.data` 表头与单元格边框)。

`_ViewStart.cshtml` 文件包含一行核心设置:`@{ Layout = "~/Views/Shared/_Layout.cshtml"; }`。框架会在渲染每个视图前自动先执行该文件,从而免去在每个视图顶部重复指定布局路径;若删去 `_ViewStart.cshtml`,就必须在各个视图中逐一声明 `Layout`。需补充一个常见工程细节:默认模板中全局生效的 `_ViewStart.cshtml` 实际置于 `Views/_ViewStart.cshtml`(作用域覆盖 `Views/` 下全部子目录),若单独放到 `Views/Shared/` 则仅作用于 `Shared` 目录内视图;某个独立页面若需切换或禁用布局,也可在该视图内显式覆盖 `Layout = null;`。

离线校验 _Layout.cshtml 渲染与 XSS 转义、@Url.Content 路径解析与 _ViewStart 注入

含完整源码 · 159 行
展开查看收起
python
"""Offline ASP.NET MVC layout & styling verification lab for Chapter 29 (mvc-layout)."""
import html
import json
import re

VERSION = "CPython 3.12.14 offline ASP.NET MVC Razor layout semantic verifier (IIS/ASP.NET host absent)"


def render_layout(title, body_html, app_root="/"):
    def url_content(tilde_path):
        assert tilde_path.startswith("~/")
        prefix = app_root.rstrip("/")
        return f"{prefix}/{tilde_path[2:]}"

    def action_link(text, action, controller):
        href = "/" if (controller == "Home" and action == "Index") else f"/{controller}/{action}"
        return f'<a href="{href}">{html.escape(text)}</a>'

    nav = (
        '<ul id="menu">'
        f'<li>{action_link("Home", "Index", "Home")}</li>'
        f'<li>{action_link("Movies", "Index", "Movies")}</li>'
        f'<li>{action_link("About", "About", "Home")}</li>'
        "</ul>"
    )
    return (
        "<!DOCTYPE html><html><head><meta charset=\"utf-8\" />"
        f"<title>{html.escape(title)}</title>"
        f'<link href="{url_content("~/Content/Site.css")}" rel="stylesheet" type="text/css" />'
        f"</head><body>{nav}"
        f'<section id="main">{body_html}<p>Copyright MvcDemo. All Rights Reserved.</p></section>'
        "</body></html>"
    )


def case_layout_cshtml_renderbody_and_xss_escape():
    rendered = render_layout(
        title='Home <script>alert(1)</script>',
        body_html="<h1>Welcome</h1><p>Content body</p>",
    )
    expected = {
        "title_escaped": "<title>Home &lt;script&gt;alert(1)&lt;/script&gt;</title>" in rendered,
        "no_raw_script_tag": "<script>alert(1)</script>" not in rendered,
        "body_inserted": '<section id="main"><h1>Welcome</h1><p>Content body</p>' in rendered,
    }
    actual = {
        "title_escaped": "<title>Home &lt;script&gt;alert(1)&lt;/script&gt;</title>" in rendered,
        "no_raw_script_tag": "<script>alert(1)</script>" not in rendered,
        "body_inserted": '<section id="main"><h1>Welcome</h1><p>Content body</p>' in rendered,
    }
    return {
        "name": "layout_cshtml_renderbody_and_xss_escape",
        "summary": "模拟 _Layout.cshtml 的 @ViewBag.Title 默认 HTML 编码防 XSS 与 @RenderBody() 视图正文注入",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_url_content_and_actionlink_helpers():
    rendered_root = render_layout("Demo", "<p>ok</p>", app_root="/")
    rendered_sub = render_layout("Demo", "<p>ok</p>", app_root="/mvcdemo")
    expected = {
        "root_css_href": True,
        "subapp_css_href": True,
        "nav_links": [
            '<a href="/">Home</a>',
            '<a href="/Movies/Index">Movies</a>',
            '<a href="/Home/About">About</a>',
        ],
    }
    actual = {
        "root_css_href": 'href="/Content/Site.css"' in rendered_root,
        "subapp_css_href": 'href="/mvcdemo/Content/Site.css"' in rendered_sub,
        "nav_links": re.findall(r'<a href="[^"]+">[^<]+</a>', rendered_root),
    }
    return {
        "name": "url_content_and_actionlink_helpers",
        "summary": "验证 @Url.Content('~/Content/Site.css') 虚拟根路径解析与 @Html.ActionLink() 导航链接输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_site_css_rule_groups_check():
    css = (
        'body{font: "Trebuchet MS", Verdana, sans-serif;background-color:#5c87b2;color:#696969;}'
        'h1{border-bottom:3px solid #cc9900;color:#996600;}'
        '#main{padding:20px;background-color:#ffffff;border-radius:0 4px 4px 4px;}'
        'ul#menu{padding:0px;position:relative;margin:0;}'
        'ul#menu li{display:inline;}'
        'ul#menu li a{background-color:#e8eef4;padding:10px 20px;border-radius:4px 4px 0 0;}'
        'fieldset{padding-left:12px;}'
        'input[type="text"], input[type="password"]{width:300px;}'
        'table.data{border:1px solid #c3c3c3;border-collapse:collapse;width:100%;}'
    )
    selectors = ["body", "h1", "#main", "ul#menu", "fieldset", "table.data"]
    expected = {
        "all_core_selectors_present": True,
        "balanced_braces": True,
        "uses_border_radius": True,
    }
    actual = {
        "all_core_selectors_present": all(sel in css for sel in selectors),
        "balanced_braces": css.count("{") == css.count("}"),
        "uses_border_radius": "border-radius" in css,
    }
    return {
        "name": "site_css_rule_groups_check",
        "summary": "校验 Site.css 中页面基础样式、菜单标签(ul#menu)、表单(fieldset)与数据表(table.data)规则完整性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_viewstart_default_layout_injection():
    viewstart_layout = "~/Views/Shared/_Layout.cshtml"

    def resolve_layout(view_override=None, has_viewstart=True):
        if view_override is not None:
            return view_override
        return viewstart_layout if has_viewstart else None

    expected = {
        "default_with_viewstart": "~/Views/Shared/_Layout.cshtml",
        "explicit_override": "~/Views/Shared/_AdminLayout.cshtml",
        "disabled_layout": "",
        "without_viewstart": None,
    }
    actual = {
        "default_with_viewstart": resolve_layout(),
        "explicit_override": resolve_layout(view_override="~/Views/Shared/_AdminLayout.cshtml"),
        "disabled_layout": resolve_layout(view_override=""),
        "without_viewstart": resolve_layout(has_viewstart=False),
    }
    return {
        "name": "viewstart_default_layout_injection",
        "summary": "验证 _ViewStart.cshtml 自动为所有视图注入默认 Layout、单页覆盖及删除 _ViewStart 后的回退行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_layout_cshtml_renderbody_and_xss_escape(),
        case_url_content_and_actionlink_helpers(),
        case_site_css_rule_groups_check(),
        case_viewstart_default_layout_injection(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线验证器确认 @ViewBag.Title 自动转义恶意 script 标签、@RenderBody() 正常注入、@Url.Content 支持子目录部署、Site.css 规则完整且 _ViewStart 覆盖逻辑准确。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2794.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:ASP.NET

课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2794.zip

下载课程关联工程包:ASP.NET

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2812.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

在该特定视图文件顶部显式覆盖写明 `@{ Layout = null; }`(或在控制器中返回 `PartialView()`),即可跳过 `_ViewStart.cshtml` 注入的默认共享布局。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习