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

WebPages 全局

剖析 ASP.NET Web Pages 两大全局启动页 _AppStart 与 _PageStart 的执行时机、作用域、RunPage() 控制机制,并说明现代 ASP.NET Core 的对应架构。

学完这一章,你能够

  • 剖析 ASP.NET Web Pages 两大全局启动页 _AppStart 与 _PageStart 的执行时机、作用域、RunPage() 控制机制,并说明现代 ASP.NET Core 的对应架构。

站点首次启动之前:_AppStart

通常情况下,处理表单或业务逻辑的服务器端代码写在各自的独立网页中;但在站点启动阶段,往往需要集中执行一次全局初始化。为此,可以在网站根目录下创建 `_AppStart.cshtml`(或 VB 站点的 `_AppStart.vbhtml`,扩展名需与站点页面一致)。只要该文件存在,ASP.NET 就会在站点收到首个请求时优先运行 `_AppStart`,用于初始化全局配置、计数器、共享名称、数据库连接或邮件服务参数。同时,由于文件名带有下划线 `_` 前缀,访客无法通过浏览器直接打开或下载 `_AppStart` 文件。

每个页面执行之前:_PageStart

与站点级只执行一次的 `_AppStart` 不同,`_PageStart` 用于在目标文件夹内的每一个页面运行之前执行前置逻辑。开发者可以为网站中的根目录及任意子文件夹分别放置 `_PageStart.cshtml`;其最典型的两个用途是为整个文件夹下的所有页面统一设置 `Layout` 布局模板,以及在进入受保护页面之前统一校验当前用户的登录与权限状态。

请求执行顺序、RunPage() 与现代 ASP.NET Core 对照

当服务器收到一个页面请求时,ASP.NET Web Pages 按固定顺序调度(原页此处附有请求生命周期流程图,未入本地缓存,已在待办项登记):首先检查根目录是否存在 `_AppStart`,若存在且当前是站点启动后的第一个请求,则先运行 `_AppStart`;接着检查请求路径上的 `_PageStart`,若存在则在目标页面之前执行 `_PageStart`。默认情况下,被请求的页面会在 `_PageStart` 执行完毕后自动运行;如果希望在目标页面执行前后都插入包裹逻辑,可在 `_PageStart` 中显式调用 `RunPage()` 精确指定内容页的运行位置。在现代 ASP.NET Core Razor Pages 中,`_AppStart` 的全局启动职责由 `Program.cs` 中的应用构建与服务注册接管,`_PageStart` 的统一布局配置对应 `_ViewStart.cshtml`,而登录认证与权限拦截则通过中间件管道与 `[Authorize]` 策略过滤器统一实现。

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

含完整源码 · 149 行
展开查看收起
python
"""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()
离线验证器确认 _AppStart 仅在首个请求运行一次、_PageStart 对未登录访问返回 302 并为已登录请求绑定布局、显式 RunPage() 精确插入前后生命周期钩子、直访下划线文件返回 404。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`_AppStart.cshtml` 仅在应用程序启动收到第 1 个请求时执行 1 次;而 `/Admin/_PageStart.cshtml` 会在每次请求 `/Admin` 目录下的页面前都执行,因此共执行 100 次(除非中途发生重定向拦截)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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