蓝色天空网mbsky.com · 知识 · 实践 · 创造ASP · 本地阅读预览
教程 / 后端开发 / ASP

ASP #include

详述 Classic ASP 服务端预处理指令 #include 的展开时机、virtual 与 file 路径差异、.inc 源码泄露风险、分隔符嵌套禁忌与循环引用防护,并离线实测预处理器。

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

学完这一章,你能够

#include 预处理机制与典型复用方式

服务器端 `#include` 指令允许在 ASP 引擎执行脚本之前,将外部文件原样插入当前 ASP 文件,常用于复用页眉、页脚、导航栏或公共函数库。例如 `mypage.asp` 依次引入纯文本片段 `wisdom.inc` 与含脚本的 `time.inc`(内部执行 `Response.Write(Time)`),预处理合并再执行后,浏览器仅看到整合完成的纯 HTML 文本与时间结果(离线实验以固定时钟 `11:33:42 AM` 核对完整合并 HTML)。

引用语法:virtual 与 file 关键词的区别

`#include` 必须写在 HTML 注释标记内,支持两种路径模式:`<!--#include virtual="..."-->` 与 `<!--#include file="..."-->`。`virtual` 始终以站点虚拟根目录 `/` 为起点(如 `virtual="/html/header.inc"`);`file` 则以当前包含指令所在文件的目录为相对起点(例如位于 `/html/` 目录下的页面引用子目录 `headers` 中的文件应写作 `file="headers/header.inc"`——需留意早期示例排版中常因反斜杠转义丢失而误印为 `headersheader.inc`,实际必须保留目录分隔符;若主页面移出 `html` 目录,该相对路径即告失效)。本站离线预处理器核验了 `/html/page.asp` 同时展开两种指令准确输出 `[VIRTUAL-HDR] | [REL-HDR]`。

安全规范、预处理先后顺序与分隔符边界

安全上强烈建议将被引用文件命名为 `.asp` 而非 `.inc`:在 IIS 默认配置中,`.inc` 往往被当作普通静态文本直接下载,访客若猜到路径就能直接看到其中的数据库连接串或敏感逻辑;改用 `.asp` 扩展名后,即使直接访问也会经过 ASP 引擎解析而不暴露源码。此外,被引用文件可继续嵌套引用其他文件,同一页面也可多次引用同一文件,但工程上必须避免循环引用(离线预处理器实测多层嵌套与重复引用输出 `A(B[C])+(B[C])`,并拦截 `loop1.asp -> loop2.asp -> loop1.asp` 抛出 `RecursionError`)。

两条最易踩坑的编译期铁律:第一,`#include` 在任何脚本执行之前就已完成静态展开,因此无法用脚本变量动态拼接文件名(`<!--#include file="<%fname%>"-->` 会把字面量 `<%fname%>` 当作文件名导致找不到文件,若需运行时动态执行另一页面应改用 `Server.Execute`);第二,不得将 `#include` 直接放进 `<% ... %>` 脚本分隔符内部,必须先以 `%>` 闭合脚本块、写完 `<!--#include ...-->` 后再以 `<%` 重新打开(如 `<% For i = 1 To n %> <!--#include file="count.inc"--> <% Next %>`)。离线预处理器精确复现了上述两类错误拦截与合法循环展开。现代 ASP.NET Core 已由 Razor 布局页(`_Layout.cshtml`)与分部视图取代静态文本拼接。

离线运行 Classic ASP #include 预处理器并校验路径、执行时机、分隔符规则与循环防护

python · 阅读源码
"""Offline Classic ASP / VBScript verifier for Chapter 11 (incfiles)."""
from __future__ import annotations

import json
import posixpath
import re

VERSION = "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)"

INCLUDE_RE = re.compile(r'<!--\s*#include\s+(virtual|file)\s*=\s*"([^"]+)"\s*-->', re.IGNORECASE)


def preprocess_includes(
    vfs: dict[str, str],
    current_path: str,
    stack: tuple[str, ...] = (),
) -> str:
    """Expand Classic ASP #include virtual/file directives BEFORE script execution with cycle guard."""
    if current_path in stack:
        raise RecursionError(f"Circular #include detected: {' -> '.join((*stack, current_path))}")
    if current_path not in vfs:
        raise FileNotFoundError(f"Included file not found: {current_path}")
    text = vfs[current_path]

    # Reject #include placed inside <% ... %> script delimiters
    for script_block in re.findall(r"<%(.*?)%>", text, flags=re.DOTALL):
        if INCLUDE_RE.search(script_block):
            raise SyntaxError("#include directive cannot appear inside <% ... %> script delimiters")

    base_dir = posixpath.dirname(current_path) or "/"

    def replace_directive(match: re.Match[str]) -> str:
        kind = match.group(1).lower()
        target = match.group(2)
        if "<%" in target or "%>" in target:
            raise FileNotFoundError(f"Preprocessor runs before script evaluation; literal path invalid: {target}")
        if kind == "virtual":
            resolved = posixpath.normpath("/" + target.lstrip("/"))
        else:
            resolved = posixpath.normpath(posixpath.join(base_dir, target))
        if not resolved.startswith("/"):
            raise ValueError(f"Invalid path: {resolved}")
        return preprocess_includes(vfs, resolved, (*stack, current_path))

    return INCLUDE_RE.sub(replace_directive, text)


def main() -> None:
    vfs = {
        "/mypage.asp": (
            "<!DOCTYPE html><html>\n<body>\n"
            "<h3>Words of Wisdom:</h3>\n"
            '<p><!--#include file="wisdom.inc"--></p>\n'
            "<h3>The time is:</h3>\n"
            '<p><!--#include file="time.inc"--></p>\n'
            "</body>\n</html>"
        ),
        "/wisdom.inc": '"One should never increase, beyond what is necessary,\nthe number of entities required to explain anything."',
        "/time.inc": "<%\nResponse.Write(Time)\n%>",
        "/html/page.asp": '<!-- #include virtual="/html/header.inc" --> | <!-- #include file="headers/header.inc" -->',
        "/html/header.inc": "[VIRTUAL-HDR]",
        "/html/headers/header.inc": "[REL-HDR]",
        "/bad_dyn.asp": '<% fname="header.inc" %>\n<!--#include file="<%fname%>"-->',
        "/bad_inside.asp": '<% For i = 1 To 3\n<!--#include file="count.inc"-->\nNext %>',
        "/good_loop.asp": '<% For i = 1 To 3 %><!--#include file="count.inc"--><% Next %>',
        "/count.inc": "X",
        "/a.asp": 'A(<!--#include file="b.asp"-->)+(<!--#include file="b.asp"-->)',
        "/b.asp": 'B[<!--#include file="c.asp"-->]',
        "/c.asp": "C",
        "/loop1.asp": '<!--#include file="loop2.asp"-->',
        "/loop2.asp": '<!--#include file="loop1.asp"-->',
    }

    expanded = preprocess_includes(vfs, "/mypage.asp")
    rendered = expanded.replace("<%\nResponse.Write(Time)\n%>", "11:33:42 AM")

    virt_and_rel = preprocess_includes(vfs, "/html/page.asp")

    dyn_err = ""
    try:
        preprocess_includes(vfs, "/bad_dyn.asp")
    except FileNotFoundError as exc:
        dyn_err = type(exc).__name__

    inside_err = ""
    try:
        preprocess_includes(vfs, "/bad_inside.asp")
    except SyntaxError as exc:
        inside_err = type(exc).__name__

    good_loop_expanded = preprocess_includes(vfs, "/good_loop.asp")

    nested_ok = preprocess_includes(vfs, "/a.asp")
    cycle_err = ""
    try:
        preprocess_includes(vfs, "/loop1.asp")
    except RecursionError as exc:
        cycle_err = type(exc).__name__

    cases = [
        {
            "name": "include_file_and_time_expansion",
            "summary": "预处理展开 mypage.asp 中的 wisdom.inc 与 time.inc 并执行固定时钟输出",
            "expected": (
                "<!DOCTYPE html><html>\n<body>\n"
                "<h3>Words of Wisdom:</h3>\n"
                '<p>"One should never increase, beyond what is necessary,\n'
                'the number of entities required to explain anything."</p>\n'
                "<h3>The time is:</h3>\n"
                "<p>11:33:42 AM</p>\n"
                "</body>\n</html>"
            ),
            "actual": rendered,
            "passed": True,
        },
        {
            "name": "include_virtual_vs_relative_file",
            "summary": "对比 virtual 虚拟目录根路径与 file 相对当前目录路径的解析结果",
            "expected": "[VIRTUAL-HDR] | [REL-HDR]",
            "actual": virt_and_rel,
            "passed": True,
        },
        {
            "name": "preprocess_order_and_delimiter_rules",
            "summary": "核对预处理先于脚本执行(动态文件名失败)、<% 内禁用 #include 及闭合分隔符后循环引用生效",
            "expected": {
                "dynamic_filename_error": "FileNotFoundError",
                "inside_script_error": "SyntaxError",
                "valid_loop_expanded": "<% For i = 1 To 3 %>X<% Next %>",
            },
            "actual": {
                "dynamic_filename_error": dyn_err,
                "inside_script_error": inside_err,
                "valid_loop_expanded": good_loop_expanded,
            },
            "passed": True,
        },
        {
            "name": "nested_include_and_cycle_guard",
            "summary": "验证多层嵌套引用与重复引用正常展开,并拦截循环引用防止死循环",
            "expected": {
                "nested_and_repeated": "A(B[C])+(B[C])",
                "cycle_error": "RecursionError",
            },
            "actual": {
                "nested_and_repeated": nested_ok,
                "cycle_error": cycle_err,
            },
            "passed": True,
        },
    ]
    for c in cases:
        c["passed"] = c["actual"] == c["expected"]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 mypage.asp 展开输出、virtual vs file 路径解析、拦截动态文件名与 <% 内嵌套 #include、通过循环体外部展开,以及嵌套与循环引用守卫。
离线运行 Classic ASP #include 预处理器并校验路径、执行时机、分隔符规则与循环防护

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:4833765eb6da239a760f24f843dd0641bf88ff2f0e47bc807198191335704dfd

下载本站示例源码

本地运行

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

下载ASP #include实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:8e1a5ffda2cbf11b015d46fa4eaedb0b06bb17d95040c782e57667f74cc19f39

常见错误与边界

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

练习与解答

为什么在 Classic ASP 中把包含数据库密码的公共文件命名为 `db.inc` 存在严重安全风险?为什么 `<!--#include file="<%fname%>"-->` 无法实现动态包含?

展开参考解答

IIS 默认不将 `.inc` 交由 ASP 引擎编译,直接请求 `/db.inc` 会把源码明文返回给浏览器,故应改用 `.asp` 扩展名;`#include` 属于脚本执行前的静态文本预处理阶段,此时变量 `fname` 尚未求值,无法动态解析文件名。

规范与官方依据