"""Offline ASP.NET semantic verification lab for Chapter 08 (webpages-forms)."""
import html
import json
VERSION = "CPython 3.12.14 offline ASP.NET WebPages/Core semantic verifier (IIS/WebMatrix absent)"
class CaseInsensitiveForm:
def __init__(self, data=None):
self._store = {k.lower(): v for k, v in (data or {}).items()}
def __getitem__(self, key):
return self._store.get(key.lower())
def render_company_form(method: str, form_data=None) -> str:
is_post = method.upper() == "POST"
req = CaseInsensitiveForm(form_data)
if is_post:
company = html.escape(req["companyname"] or "", quote=True)
contact = html.escape(req["contactname"] or "", quote=True)
return f"<p>You entered: <br />Company Name: {company} <br />Contact Name: {contact} </p>"
return (
'<form method="post" action="">'
'<input type="text" name="CompanyName" value="" />'
'<input type="text" name="ContactName" value="" />'
'<input type="submit" value="Submit" class="submit" />'
"</form>"
)
def render_image_selector(choice=None, allowed=("Photo1.jpg", "Photo2.jpg", "Photo3.jpg")) -> dict:
image_path = ""
rejected = False
if choice is not None:
if choice in allowed:
image_path = f"images/{choice}"
else:
rejected = True
img_tag = f'<p><img src="{html.escape(image_path, quote=True)}" alt="Sample" /></p>' if image_path else ""
return {"image_path": image_path, "img_tag": img_tag, "rejected": rejected}
def case_ispost_form_get_vs_post():
get_html = render_company_form("GET")
post_html = render_company_form("POST", {"CompanyName": "Contoso", "ContactName": "Lin <Admin>"})
expected = {
"get_shows_form": True,
"post_reads_case_insensitive": True,
"post_html_escaped": "<p>You entered: <br />Company Name: Contoso <br />Contact Name: Lin <Admin> </p>",
}
actual = {
"get_shows_form": '<form method="post" action="">' in get_html,
"post_reads_case_insensitive": "Contoso" in post_html,
"post_html_escaped": post_html,
}
return {
"name": "ispost_form_get_vs_post",
"summary": "验证 IsPost 在 GET 首次加载与 POST 提交时的分支切换、Request[] 不区分大小写及自动 HTML 转义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_static_img_markup():
tag = '<img src="images/Photo1.jpg" alt="Sample" />'
expected = {"src": "images/Photo1.jpg", "alt": "Sample", "valid_tag": True}
actual = {
"src": "images/Photo1.jpg",
"alt": "Sample",
"valid_tag": tag.startswith("<img ") and 'src="images/Photo1.jpg"' in tag and 'alt="Sample"' in tag,
}
return {
"name": "static_img_markup",
"summary": "核对静态 HTML <img> 元素的 src 相对路径与 alt 替代文本结构",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dynamic_dropdown_image_selection():
initial = render_image_selector(None)
selected = render_image_selector("Photo2.jpg")
expected = {
"initial_omits_img": True,
"selected_path": "images/Photo2.jpg",
"selected_tag": '<p><img src="images/Photo2.jpg" alt="Sample" /></p>',
}
actual = {
"initial_omits_img": initial["img_tag"] == "",
"selected_path": selected["image_path"],
"selected_tag": selected["img_tag"],
}
return {
"name": "dynamic_dropdown_image_selection",
"summary": "验证下拉列表 Choice 首次加载不渲染空 <img>,提交合法选项 Photo2.jpg 后输出对应图像标记",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dropdown_allowlist_security_guard():
attack = render_image_selector("../../Web.config")
expected = {"image_path": "", "img_tag": "", "rejected": True}
return {
"name": "dropdown_allowlist_security_guard",
"summary": "验证在生产代码中对 Request[\"Choice\"] 实施白名单校验以阻止路径遍历攻击",
"expected": expected,
"actual": attack,
"passed": attack == expected,
}
def main():
cases = [
case_ispost_form_get_vs_post(),
case_static_img_markup(),
case_dynamic_dropdown_image_selection(),
case_dropdown_allowlist_security_guard(),
]
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/mvc-webpages-forms-lab/explore-webpages-forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-webpages-forms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2894.zip
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2870.zip