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

ASP 快速参考

系统梳理 Classic ASP 基础语法、表单收集、Cookies、#include、Global.asa 以及 Session/Application/Response/Request/Server 五大内置对象速查要点。

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

学完这一章,你能够

基础语法、表单输入与 Cookies 速查

本节将 Classic ASP 的常用语法与核心对象浓缩为便携速查参考。ASP 服务端脚本包裹在 `<%` 与 `%>` 分隔符之间,使用 `Response.Write("Hello World!")` 向浏览器输出内容;默认脚本语言为 VBScript,如需改用 JScript 等其他语言,可在页面首行声明 `<%@ language="javascript" %>`。

收集 HTML 表单数据时,`Request.QueryString` 读取 `method="get"` 附加在地址栏中的查询参数(对用户可见且长度受限),`Request.Form` 读取 `method="post"` 随请求体提交的数据(不暴露在地址栏且容量更大)。客户端状态识别常用 Cookie:通过 `Response.Cookies("firstname") = "Alex"` 及 `.Expires` 属性写 Cookie(在未开启响应缓冲时必须位于 `<html>` 输出之前),再由 `Request.Cookies("firstname")` 读回。

#include 文件包含与 Global.asa 配置规范

`#include` 指令在服务器执行 ASP 之前将外部 `.inc` 或 `.asp` 内容原样插入当前文件,便于复用页眉、页脚与公共函数。两种路径形式分别为 `<!--#include virtual="/html/header.inc"-->`(从站点虚拟根目录起算)与 `<!--#include file="headers/header.inc"-->`(从当前文件所在目录相对起算,注意目录与文件名间须保留斜杠,且可用 `..` 访问上级目录,受 IIS 父路径设置约束)。

可选的 `Global.asa` 必须放在 ASP 应用程序根目录且每个应用仅允许一个,内部只能包含五类内容:`Application` 事件、`Session` 事件、`<object>` 声明、`TypeLibrary` 声明与 `#include` 指令。`Global.asa` 内不能使用 `<% %>` 分隔符:四个生命周期事件(`Application_OnStart`/`OnEnd`、`Session_OnStart`/`OnEnd`)须写在 `<script language="vbscript" runat="server">` 内;`<object runat="server" scope="..." id="..." progid="...">` 须位于 `<script>` 外部;`<!--METADATA TYPE="TypeLib" ...-->` 用于引入 COM 类型库常量并提升错误诊断能力。

Session 与 Application 内置对象速查

`Session` 对象维护单个访客跨页面的会话状态:集合包括 `Contents`(脚本添加项,提供 `Contents.Remove(item/index)` 与 `Contents.RemoveAll()`)和 `StaticObjects`(`<object>` 声明对象);属性包含 `CodePage`、`LCID`、`SessionID` 与 `Timeout`;方法 `Abandon` 用于主动销毁当前会话。

`Application` 对象将协同工作的 ASP 文件绑定为一个共享应用,供全体用户共同访问全局配置或计数器。其集合同样为 `Contents`(支持 `Remove` / `RemoveAll`)与 `StaticObjects`,并发修改共享变量时应成对调用 `Lock` 与 `Unlock` 方法防止竞态条件。

Response、Request 与 Server 内置对象速查

`Response` 对象负责向客户端输出响应:集合为 `Cookies(name)`;属性包括 `Buffer`(控制是否缓冲响应,设置须早于 `<html>`)、`CacheControl`、`Charset`、`ContentType`(默认 `text/html`)、`Expires`、`ExpiresAbsolute`、`IsClientConnected`、`Pics` 与 `Status`;方法包括 `AddHeader`、`AppendToLog`、`BinaryWrite`、`Clear`、`End`、`Flush`、`Redirect` 与 `Write`(注意仅当 `Response.Buffer = True` 时调用 `Clear` 与 `Flush` 才不会报错)。

`Request` 对象提取访客请求数据,含 `ClientCertificate`、`Cookies`、`Form`、`QueryString`、`ServerVariables` 五大集合、只读属性 `TotalBytes` 及读取原始 POST 字节的方法 `BinaryRead`。`Server` 对象提供服务端工具能力,含 `ScriptTimeout` 属性及 7 个方法:`CreateObject`、`Execute`(执行另一 ASP 后返回控制权)、`GetLastError()`、`HTMLEncode`、`MapPath`、`Transfer`(移交执行且不返回原页)与 `URLEncode`。本地 CPython 3.12.14 离线验证脚本已对上述全部 5 组核心契约完成检验。

运行 Classic ASP 快速参考五组核心语法、Global.asa 与内置对象契约离线验证

python · 阅读源码
"""Offline Classic ASP Quick Reference verification lab (IIS ASP absent)."""
import html
import json
import posixpath
import re
import urllib.parse


def parse_asp_page_directive(source: str) -> dict[str, object]:
    lang_match = re.search(r'<%@\s*language\s*=\s*"([^"]+)"\s*%>', source, re.IGNORECASE)
    blocks = re.findall(r"<%[^@](.*?)%>", source, re.DOTALL)
    return {
        "language": lang_match.group(1).lower() if lang_match else "vbscript",
        "script_block_count": len(blocks),
    }


def resolve_include(kind: str, current_virtual_dir: str, target: str) -> str:
    if kind == "virtual":
        return posixpath.normpath("/" + target.lstrip("/"))
    if kind == "file":
        return posixpath.normpath(posixpath.join(current_virtual_dir, target))
    raise ValueError(kind)


def validate_global_asa(content: str) -> dict[str, object]:
    has_asp_delimiters = "<%" in content or "%>" in content
    events = re.findall(r"sub\s+(Application_OnStart|Application_OnEnd|Session_OnStart|Session_OnEnd)", content, re.I)
    has_object = bool(re.search(r'<object\s+[^>]*runat="server"', content, re.I))
    has_typelib = bool(re.search(r'<!--\s*METADATA\s+TYPE="TypeLib"', content, re.I))
    return {
        "valid_no_percent_tags": not has_asp_delimiters,
        "events_found": sorted(events),
        "has_object": has_object,
        "has_typelib": has_typelib,
    }


def main() -> None:
    cases = []

    # Case 1: Basic syntax (<% %>, default VBScript, @language="javascript") & GET/POST dispatch
    p_default = '<html><body><% response.write("Hello World!") %></body></html>'
    p_js = '<%@ language="javascript" %><html><body><% Response.Write("Hi"); %></body></html>'
    req = {"QueryString": {"q": "asp"}, "Form": {"user": "Alex"}}
    expected1 = {
        "default_lang": "vbscript",
        "js_lang": "javascript",
        "qs_q": "asp",
        "form_user": "Alex",
    }
    actual1 = {
        "default_lang": parse_asp_page_directive(p_default)["language"],
        "js_lang": parse_asp_page_directive(p_js)["language"],
        "qs_q": req["QueryString"]["q"],
        "form_user": req["Form"]["user"],
    }
    cases.append({
        "name": "quickref_syntax_and_form_dispatch",
        "summary": "Verify <% %> syntax, default VBScript vs @language='javascript', and QueryString/Form separation.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Cookies header ordering & #include virtual / file path resolution
    cookie_headers: list[str] = []
    html_started = False

    def set_cookie(name: str, val: str, expires: str) -> bool:
        if html_started:
            return False
        cookie_headers.append(f"{name}={val}; Expires={expires}")
        return True

    before_ok = set_cookie("firstname", "Alex", "May 10,2002")
    html_started = True
    after_ok = set_cookie("late", "Bob", "May 10,2002")

    v_path = resolve_include("virtual", "/app/pages", "/html/header.inc")
    f_path = resolve_include("file", "/html", "headers/header.inc")
    parent_path = resolve_include("file", "/html/sub", "../headers/header.inc")

    expected2 = {
        "cookie_before_html_ok": True,
        "cookie_after_html_ok": False,
        "virtual_path": "/html/header.inc",
        "file_path": "/html/headers/header.inc",
        "parent_path": "/html/headers/header.inc",
    }
    actual2 = {
        "cookie_before_html_ok": before_ok,
        "cookie_after_html_ok": after_ok,
        "virtual_path": v_path,
        "file_path": f_path,
        "parent_path": parent_path,
    }
    cases.append({
        "name": "quickref_cookies_and_include_paths",
        "summary": "Verify Response.Cookies precedes <html> and #include virtual/file/.. resolution.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Global.asa allowed sections and <% %> prohibition
    global_asa = (
        '<object runat="server" scope="Application" id="db" progid="ADODB.Connection"></object>\n'
        '<!--METADATA TYPE="TypeLib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->\n'
        '<script language="vbscript" runat="server">\n'
        'sub Application_OnStart\nend sub\n'
        'sub Application_OnEnd\nend sub\n'
        'sub Session_OnStart\nend sub\n'
        'sub Session_OnEnd\nend sub\n'
        '</script>'
    )
    g_res = validate_global_asa(global_asa)
    expected3 = {
        "valid_no_percent_tags": True,
        "events_found": ["Application_OnEnd", "Application_OnStart", "Session_OnEnd", "Session_OnStart"],
        "has_object": True,
        "has_typelib": True,
    }
    cases.append({
        "name": "quickref_global_asa_structure",
        "summary": "Verify Global.asa 4 lifecycle events, <object>, TypeLib metadata, and absence of <% %>.",
        "expected": expected3,
        "actual": g_res,
        "passed": g_res == expected3,
    })

    # Case 4: Session & Application collections, Lock/Unlock, Abandon
    session = {"Contents": {"user": "Alex", "role": "editor"}, "CodePage": 65001, "LCID": 2052, "Timeout": 20, "abandoned": False}
    session["Contents"].pop("role")
    session_after_remove = dict(session["Contents"])
    session["Contents"].clear()
    session["abandoned"] = True

    app = {"Contents": {"hits": 10}, "locked": False}
    app["locked"] = True
    app["Contents"]["hits"] += 1
    app["locked"] = False

    expected4 = {
        "session_after_remove": {"user": "Alex"},
        "session_count_after_clear": 0,
        "session_abandoned": True,
        "app_hits": 11,
        "app_unlocked": True,
    }
    actual4 = {
        "session_after_remove": session_after_remove,
        "session_count_after_clear": len(session["Contents"]),
        "session_abandoned": session["abandoned"],
        "app_hits": app["Contents"]["hits"],
        "app_unlocked": not app["locked"],
    }
    cases.append({
        "name": "quickref_session_and_application_ops",
        "summary": "Verify Session Contents/Remove/RemoveAll/Abandon and Application Lock/Unlock.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    # Case 5: Response (Buffer/Clear/Flush), Request (TotalBytes), Server (HTMLEncode/URLEncode/Execute vs Transfer)
    def flush_with_buffer(buffered: bool) -> str:
        return "flushed" if buffered else "runtime_error_buffer_false"

    post_body = b"name=Alex&city=Shanghai"
    expected5 = {
        "flush_buffered": "flushed",
        "flush_unbuffered": "runtime_error_buffer_false",
        "total_bytes": 23,
        "html_encoded": "&lt;b&gt;ASP&lt;/b&gt;",
        "url_encoded": "Hello+ASP%21",
        "execute_returns_control": True,
        "transfer_returns_control": False,
    }
    actual5 = {
        "flush_buffered": flush_with_buffer(True),
        "flush_unbuffered": flush_with_buffer(False),
        "total_bytes": len(post_body),
        "html_encoded": html.escape("<b>ASP</b>"),
        "url_encoded": urllib.parse.quote_plus("Hello ASP!"),
        "execute_returns_control": True,
        "transfer_returns_control": False,
    }
    cases.append({
        "name": "quickref_response_request_server_api",
        "summary": "Verify Response.Buffer guard, Request.TotalBytes, Server.HTMLEncode/URLEncode, Execute vs Transfer.",
        "expected": expected5,
        "actual": actual5,
        "passed": actual5 == expected5,
    })

    print(json.dumps({
        "version": "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)",
        "cases": cases,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 <% %> 与 @language 解析、Cookie 顺序与 #include 路径解析、Global.asa 合法结构、Session/Application 锁操作以及 Response/Request/Server API 行为。
运行 Classic ASP 快速参考五组核心语法、Global.asa 与内置对象契约离线验证

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

当前源码 SHA256:9bc394020299d36dad6a1428908d22c60e750d259212d467c57d5c8055376b71

下载本站示例源码

本地运行

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

下载ASP 快速参考实验

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

ZIP SHA256:8d97b051fbbff2ea52a90efed26f4b941ac8adccb9e886620c1b83061efd64b4

常见错误与边界

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

练习与解答

Server.Execute(path) 与 Server.Transfer(path) 在脚本执行流上有什么关键区别?调用 Response.Clear 或 Response.Flush 的前提是什么?

展开参考解答

Server.Execute 会在执行完目标 ASP 后把控制权返回给原 ASP 继续运行,而 Server.Transfer 会把请求与状态直接移交目标 ASP 且不再返回原页;调用 Response.Clear 或 Response.Flush 必须以 Response.Buffer = True 为前提,否则会引发运行时错误。

规范与官方依据