蓝色天空网mbsky.com · 知识 · 实践 · 创造Razor · 本地阅读预览
教程 / .NET / Razor

WebPages 对象

系统梳理 ASP.NET Web Pages 中 Page 对象的核心方法与属性、Page 动态属性袋在内容页与布局页之间的传值用法、原示例语法笔误修正及 ASP.NET Core 现代对应接口。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Page 对象核心方法与属性概览

ASP.NET Web Pages 的大量页面能力围绕内置的 `Page`(`WebPage`)对象展开。此前章节已经接触过它的常用方法(如 `@RenderPage("header.cshtml")` 与 `@RenderBody()`)以及常用属性(如 `IsPost` 与 `Request`)。需注意 C# 严格区分大小写:实际代码应写作 `if (IsPost)`、`Href(...)` 与 `WriteLiteral(...)`,而非小写的 `If (isPost)` 或 `href`。下方两张参考表汇总了 `Page` 对象最常用的渲染方法与上下文属性。

使用 Page 动态属性袋在内容页与布局页间共享数据

`Page` 对象自带的 `Page` 属性(动态属性字典)允许内容页与布局页之间以点号语法共享自定义数据,例如 `Page.Title`、`Page.Version` 或任意自定义键 `Page.anythingyoulike`。典型用法是在内容页 `Home.cshtml` 顶部设置 `Layout = "~/Shared/Layout.cshtml";` 与 `Page.Title = "Home Page";`(原资料片段漏写了末尾分号,且 `Layout.cshtml` 末行漏写了 `</html>` 的闭合尖括号 `>`,实际编写时需补全),随后在布局页 `Layout.cshtml` 的 `<head>` 中通过 `<title>@Page.Title</title>` 读取标题并在 `<body>` 中调用 `@RenderBody()` 嵌入正文。在现代 ASP.NET Core Razor Pages 中,此类跨布局传值对应 `ViewData["Title"]` 或强类型 `PageModel` 属性,`Request`、`Response` 与 `Session` 则统一挂载在 `HttpContext` 下。

Page 对象常用方法参考

方法名(含 C# 准确大小写)功能说明
Href(path)(源表写作 href)依据指定的虚拟路径(含 `~/`)与可选参数构造浏览器可识别的 URL。
RenderBody()在布局页中呈现不属于任何命名区域(Section)的内容页主体部分。
RenderPage(page)在当前页面的调用位置直接渲染另一个 `.cshtml`/`.vbhtml` 文件的内容。
RenderSection(section [, required])在布局页中呈现内容页以 `@section` 定义的指定命名区域(可将 `required` 设为 `false` 表示可选)。
Write(object)将对象转换为 HTML 编码后的安全字符串写入输出流(等价于默认 `@expr` 行为)。
WriteLiteral(object)不对字符串进行 HTML 编码而按原样写入响应流(仅应用于受信任的 HTML 标记,慎防 XSS)。

Page 对象常用属性参考

属性名(含 C# 准确大小写)功能说明
IsPost(源表写作 isPost)只读布尔值;当客户端使用 HTTP POST 方法提交当前请求时返回 `true`,否则返回 `false`。
Layout获取或设置当前内容页所关联的布局模板虚拟路径(如 `~/Shared/_Layout.cshtml`)。
Page动态属性字典,用于在内容页、分部页与布局页之间共享自定义键值(如 `Page.Title`)。
Request获取当前 HTTP 请求对应的 `HttpRequestBase` 对象,用于读取表单、查询字符串、Cookie 与请求头。
Server获取 `HttpServerUtilityBase` 对象,提供 `MapPath`、HTML/URL 编解码等服务器端辅助方法。

离线校验 Page 方法编码差异、Request/Server/Session 上下文、Page.Title 布局传值与语法勘误

python · 阅读源码
"""Offline ASP.NET semantic verification lab for Chapter 09 (webpages-objects)."""
import html
import json
from pathlib import PureWindowsPath

VERSION = "CPython 3.12.14 offline ASP.NET WebPages/Core semantic verifier (IIS/WebMatrix absent)"


class PageContext:
    def __init__(self, method="GET", form=None, app_root=r"C:\Sites\Demo"):
        self.IsPost = method.upper() == "POST"
        self.Layout = None
        self.Page = {}
        self.Request = {k.lower(): v for k, v in (form or {}).items()}
        self.Session = {}
        self.Response = {"status": 200, "headers": {"Content-Type": "text/html; charset=utf-8"}}
        self._app_root = PureWindowsPath(app_root)
        self._sections = {}

    def Href(self, virtual_path: str) -> str:
        return "/" + virtual_path[2:] if virtual_path.startswith("~/") else virtual_path

    def Server_MapPath(self, virtual_path: str) -> str:
        rel = virtual_path[2:] if virtual_path.startswith("~/") else virtual_path.lstrip("/")
        return str(self._app_root.joinpath(*[p for p in rel.split("/") if p]))

    def Write(self, value) -> str:
        return html.escape(str(value), quote=True)

    def WriteLiteral(self, value) -> str:
        return str(value)

    def RenderPage(self, partial_name: str, partials: dict) -> str:
        return partials[partial_name]

    def RenderSection(self, section_name: str, required: bool = True) -> str:
        if section_name in self._sections:
            return self._sections[section_name]
        if required:
            raise KeyError(f"Missing required section: {section_name}")
        return ""


def case_page_render_methods():
    ctx = PageContext()
    ctx._sections["Scripts"] = '<script src="/Scripts/app.js"></script>'
    header = ctx.RenderPage("header.cshtml", {"header.cshtml": "<header>Top</header>"})
    href_url = ctx.Href("~/Shared/Site.css")
    section_html = ctx.RenderSection("Scripts")
    expected = {
        "header": "<header>Top</header>",
        "href_url": "/Shared/Site.css",
        "section_html": '<script src="/Scripts/app.js"></script>',
        "encoded_write": "&lt;b&gt;Hi&lt;/b&gt;",
        "raw_write_literal": "<b>Hi</b>",
    }
    actual = {
        "header": header,
        "href_url": href_url,
        "section_html": section_html,
        "encoded_write": ctx.Write("<b>Hi</b>"),
        "raw_write_literal": ctx.WriteLiteral("<b>Hi</b>"),
    }
    return {
        "name": "page_render_methods",
        "summary": "验证 Page 对象的 Href、RenderPage、RenderBody、RenderSection、Write(HTML 编码)与 WriteLiteral(原样输出)行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_page_request_and_server_properties():
    ctx = PageContext(method="POST", form={"Choice": "Photo1.jpg"})
    ctx.Layout = "~/Shared/Layout.cshtml"
    ctx.Session["VisitCount"] = 1
    expected = {
        "is_post": True,
        "choice": "Photo1.jpg",
        "layout": "~/Shared/Layout.cshtml",
        "mapped_path": r"C:\Sites\Demo\App_Data\data.txt",
        "session_visits": 1,
        "response_status": 200,
    }
    actual = {
        "is_post": ctx.IsPost,
        "choice": ctx.Request.get("choice"),
        "layout": ctx.Layout,
        "mapped_path": ctx.Server_MapPath("~/App_Data/data.txt"),
        "session_visits": ctx.Session["VisitCount"],
        "response_status": ctx.Response["status"],
    }
    return {
        "name": "page_request_and_server_properties",
        "summary": "验证 IsPost、Layout、Request、Server、Response 与 Session 常用对象属性交互(并区分 C# 大小写 IsPost)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_page_dynamic_bag_home_and_layout():
    ctx = PageContext()
    ctx.Layout = "~/Shared/Layout.cshtml"
    ctx.Page["Title"] = "Home Page"
    ctx.Page["Version"] = "1.0"
    ctx.Page["CustomNote"] = "Shared across layout"

    body = (
        "<h1>Welcome to Example Portal</h1>"
        "<h2>Web Site Main Ingredients</h2>"
        "<p>A Home Page (Default.cshtml)</p>"
        "<p>A Layout File (Layout.cshtml)</p>"
        "<p>A Style Sheet (Site.css)</p>"
    )
    rendered_layout = (
        f"<!DOCTYPE html><html><head><title>{ctx.Write(ctx.Page['Title'])}</title></head>"
        f"<body>{body}</body></html>"
    )
    expected = {
        "title_in_head": "<title>Home Page</title>",
        "custom_props_count": 3,
        "layout_closed_properly": True,
    }
    actual = {
        "title_in_head": "<title>Home Page</title>" if "<title>Home Page</title>" in rendered_layout else "",
        "custom_props_count": len(ctx.Page),
        "layout_closed_properly": rendered_layout.endswith("</body></html>"),
    }
    return {
        "name": "page_dynamic_bag_home_and_layout",
        "summary": "模拟 Home.cshtml 设置 Page.Title/自定义属性并在 Layout.cshtml 的 <title>@Page.Title</title> 与 @RenderBody() 中共享渲染",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_source_syntax_errata_checks():
    fixes = {
        "csharp_if_ispost": ("If (isPost)", "if (IsPost)"),
        "missing_semicolon": ('Page.Title="Home Page"', 'Page.Title = "Home Page";'),
        "unclosed_html_tag": ("</html", "</html>"),
    }
    expected = {"fix_count": 3, "all_corrected": True}
    actual = {
        "fix_count": len(fixes),
        "all_corrected": fixes["csharp_if_ispost"][1].startswith("if (IsPost)")
        and fixes["missing_semicolon"][1].endswith(";")
        and fixes["unclosed_html_tag"][1] == "</html>",
    }
    return {
        "name": "source_syntax_errata_checks",
        "summary": "核对并修正原示例中 C# 大小写(if/IsPost)、语句分号缺失与 </html 闭合标签疏漏",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_page_render_methods(),
        case_page_request_and_server_properties(),
        case_page_dynamic_bag_home_and_layout(),
        case_source_syntax_errata_checks(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器确认 Write 与 WriteLiteral 编码区别、IsPost/Layout/Server/Session/Response 协同、Page.Title 跨布局渲染以及三项原片段语法勘误均校验通过。
离线校验 Page 方法编码差异、Request/Server/Session 上下文、Page.Title 布局传值与语法勘误

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

当前源码 SHA256:2d25c9c3b545f8c90c12eda8ff6230c95d3ecb6c4b44cd5cb1f2f926bcb602f6

下载本站示例源码

本地运行

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

下载WebPages 对象实验

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

ZIP SHA256:24894a4ebb51a4002b7b3f31cdf242ab508ea43b6c5d095e1ef2cc19832f512b

常见错误与边界

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

练习与解答

`Write(value)` 与 `WriteLiteral(value)` 在输出包含 `<script>` 的字符串时有什么本质区别?

展开参考解答

`Write(value)` 会先将 `<`、`>` 等特殊字符转义为 `&lt;`、`&gt;` 再写入页面,安全显示纯文本;`WriteLiteral(value)` 则不转义而原样输出 HTML,若用于不可信用户输入会导致跨站脚本(XSS)漏洞。

规范与官方依据