"""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": "<b>Hi</b>",
"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()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。
入口文件:projects/razor-webpages-objects-lab/explore-webpages-objects.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-webpages-objects.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2925.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2955.zip