蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 _AppStart 单次初始化、_PageStart 权限与布局拦截、RunPage() 包裹及下划线访问拒绝

PYTHONWindows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。explore-webpages-global.py
explore-webpages-global.py149 行
"""Offline ASP.NET semantic verification lab for Chapter 07 (webpages-global)."""
import json

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


class WebPagesHostSimulator:
    def __init__(self, has_app_start=True, page_starts=None):
        self.has_app_start = has_app_start
        self.app_started = False
        self.app_state = {}
        self.page_starts = page_starts or {}

    def handle_request(self, path: str, user_authenticated: bool = True):
        filename = path.rsplit("/", 1)[-1]
        if filename.startswith("_"):
            return {"status": 404, "trace": ["blocked_underscore_file"], "layout": None}

        trace = []
        layout = None
        if self.has_app_start and not self.app_started:
            self.app_started = True
            self.app_state["SiteName"] = "DemoPortal"
            self.app_state["BootCount"] = self.app_state.get("BootCount", 0) + 1
            trace.append("_AppStart.cshtml")

        folder = path.rsplit("/", 1)[0] or "/"
        ps = self.page_starts.get(folder)
        if ps:
            if ps.get("require_auth") and not user_authenticated:
                trace.append(f"{folder.rstrip('/')}/_PageStart.cshtml:redirect_login")
                return {"status": 302, "trace": trace, "layout": layout}
            layout = ps.get("layout")
            if ps.get("explicit_run_page"):
                trace.append(f"{folder.rstrip('/')}/_PageStart.cshtml:before")
                trace.append(f"RunPage({path})")
                trace.append(f"{folder.rstrip('/')}/_PageStart.cshtml:after")
                return {"status": 200, "trace": trace, "layout": layout}
            trace.append(f"{folder.rstrip('/')}/_PageStart.cshtml")

        trace.append(f"Page({path})")
        return {"status": 200, "trace": trace, "layout": layout}


def case_appstart_runs_once_on_first_request():
    host = WebPagesHostSimulator(has_app_start=True)
    r1 = host.handle_request("/Default.cshtml")
    r2 = host.handle_request("/About.cshtml")
    expected = {
        "req1_trace": ["_AppStart.cshtml", "Page(/Default.cshtml)"],
        "req2_trace": ["Page(/About.cshtml)"],
        "boot_count": 1,
        "site_name": "DemoPortal",
    }
    actual = {
        "req1_trace": r1["trace"],
        "req2_trace": r2["trace"],
        "boot_count": host.app_state["BootCount"],
        "site_name": host.app_state["SiteName"],
    }
    return {
        "name": "appstart_runs_once_on_first_request",
        "summary": "验证 _AppStart.cshtml 仅在站点收到首个请求时执行一次并初始化全局状态,后续请求不再重复运行",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pagestart_layout_and_auth_guard():
    host = WebPagesHostSimulator(
        has_app_start=True,
        page_starts={
            "/Admin": {"layout": "~/Shared/_AdminLayout.cshtml", "require_auth": True},
        },
    )
    anon = host.handle_request("/Admin/Dashboard.cshtml", user_authenticated=False)
    authed = host.handle_request("/Admin/Dashboard.cshtml", user_authenticated=True)
    expected = {
        "anon_status": 302,
        "authed_status": 200,
        "authed_layout": "~/Shared/_AdminLayout.cshtml",
        "authed_trace": ["/Admin/_PageStart.cshtml", "Page(/Admin/Dashboard.cshtml)"],
    }
    actual = {
        "anon_status": anon["status"],
        "authed_status": authed["status"],
        "authed_layout": authed["layout"],
        "authed_trace": authed["trace"],
    }
    return {
        "name": "pagestart_layout_and_auth_guard",
        "summary": "验证文件夹级 _PageStart.cshtml 在目标页运行前执行登录拦截并统一指定布局页",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_explicit_runpage_lifecycle():
    host = WebPagesHostSimulator(
        has_app_start=False,
        page_starts={
            "/Reports": {"layout": "~/Shared/_ReportLayout.cshtml", "explicit_run_page": True},
        },
    )
    res = host.handle_request("/Reports/Sales.cshtml")
    expected = [
        "/Reports/_PageStart.cshtml:before",
        "RunPage(/Reports/Sales.cshtml)",
        "/Reports/_PageStart.cshtml:after",
    ]
    return {
        "name": "explicit_runpage_lifecycle",
        "summary": "验证 _PageStart.cshtml 显式调用 RunPage() 精确控制目标内容页的前后包裹执行顺序",
        "expected": expected,
        "actual": res["trace"],
        "passed": res["trace"] == expected,
    }


def case_underscore_direct_browse_denied():
    host = WebPagesHostSimulator()
    r_app = host.handle_request("/_AppStart.cshtml")
    r_page = host.handle_request("/Admin/_PageStart.cshtml")
    expected = {"appstart_status": 404, "pagestart_status": 404}
    actual = {"appstart_status": r_app["status"], "pagestart_status": r_page["status"]}
    return {
        "name": "underscore_direct_browse_denied",
        "summary": "验证带有下划线前缀的 _AppStart.cshtml 与 _PageStart.cshtml 无法被浏览器直接访问",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_appstart_runs_once_on_first_request(),
        case_pagestart_layout_and_auth_guard(),
        case_explicit_runpage_lifecycle(),
        case_underscore_direct_browse_denied(),
    ]
    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/web-forms-webpages-global-lab/explore-webpages-global.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-webpages-global.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Web Forms

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

下载课程关联工程包:Web Forms

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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