ASP Session
系统剖析 Classic ASP Session 对象的无状态 HTTP 识别机制、启动与结束条件(Timeout/Abandon)、变量读写与移除,以及 Contents 与 StaticObjects 集合遍历差异,并离线实测状态机。
学完这一章,你能够
- 系统剖析 Classic ASP Session 对象的无状态 HTTP 识别机制、启动与结束条件(Timeout/Abandon)、变量读写与移除,以及 Contents 与 StaticObjects 集合遍历差异,并离线实测状态机。
HTTP 无状态问题与 Session 对象生命周期
由于 HTTP 协议本身无状态,Web 服务器无法天然串联同一访客的多次页面请求。Classic ASP 为每位新访客签发一个唯一标识 Cookie(典型如 `ASPSESSIONID...`),并在服务器端维护对应的 `Session` 对象,使姓名、ID、偏好参数等单用户数据可在整个应用的所有页面间共享,直至会话失效时自动撤销。
Session 在以下三种情形之一触发时正式开始:新用户首次请求 ASP 文件且 `Global.asa` 中定义了 `Session_OnStart` 子程序;脚本向任意 `Session` 变量写入值;或用户请求 ASP 文件且 `Global.asa` 使用 `<object>` 标签声明了 `scope="session"` 的对象。
若用户在规定空闲时间内未请求或刷新页面,Session 将自动超时销毁,默认时长为 `20` 分钟。可通过 `Session.Timeout = 5` 调整超时分钟数,或调用 `Session.Abandon` 在当前页执行完毕后立即撤销会话。需权衡内存占用与用户体验:超时过长会消耗服务器资源,过短则迫使用户频繁重头操作,因此仅应在 Session 中存放少量轻量数据。本站离线实验验证了默认 20 分钟、调整至 5 分钟后空闲 4 分钟有效/5 分钟失效,以及 `Abandon` 在当前页仍可读但页末释放的语义。
存储、读取与移除 Session 变量
写入 `Session("username")="Donald Duck"` 与 `Session("age")=50` 后,应用内任意页面均可直接读取并渲染 `Welcome Donald Duck`;也可依据存储在 Session 中的偏好(如 `Session("screenres")="low"`)在纯文本版与多媒体版页面间条件分支(离线实验对低/高分辨率分支均核对通过)。
所有通过脚本写入的会话变量都归属于 `Session.Contents` 集合。可通过 `Session.Contents.Remove("sale")` 按条件移除单个键(如当 `age < 18` 时删除 `sale`),或调用 `Session.Contents.RemoveAll()` 一次性清空全部脚本变量。离线实验核验移除 `sale` 后剩余 `["age", "theme"]`,调用 `RemoveAll()` 后计数归 `0`。
遍历 Contents 与 StaticObjects 集合
使用 `For Each i In Session.Contents` 遍历集合时,循环变量 `i` 依次取得的是变量键名(如 `username`、`age`);若结合 `Session.Contents.Count` 使用 `For i = 1 To j` 按 1 起始下标访问 `Session.Contents(i)`,返回的则是对应的值(`Donald Duck`、`50`)。另外,通过 `Global.asa` 的 `<object>` 标签注入的会话级静态对象需遍历 `Session.StaticObjects` 集合查看(离线实测核对键名列表、1 起始键值列表及 `StaticObjects` 枚举)。作为遗留进程内状态机制,Classic ASP Session 不适合多节点无粘性负载均衡,现代项目建议改用 ASP.NET Core 分布式会话存储。
离线模拟 Session 生命周期、Timeout/Abandon、条件分支、Remove/RemoveAll 与集合遍历
展开查看收起
"""Offline Classic ASP / VBScript verifier for Chapter 09 (sessions)."""
from __future__ import annotations
import json
VERSION = "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)"
class AspSession:
def __init__(self, session_id: str, timeout: int = 20) -> None:
self.session_id = session_id
self.timeout = timeout
self.contents: dict[str, object] = {}
self.static_objects: dict[str, str] = {}
self.abandoned = False
self.active = True
def finish_request(self) -> None:
if self.abandoned:
self.contents.clear()
self.active = False
def is_expired(self, idle_minutes: int) -> bool:
return idle_minutes >= self.timeout
def contents_item_by_1based_index(self, idx: int) -> object:
return list(self.contents.values())[idx - 1]
def main() -> None:
s1 = AspSession("ASPSESSIONID-1001")
default_timeout = s1.timeout
s1.timeout = 5
expired_at_4 = s1.is_expired(4)
expired_at_5 = s1.is_expired(5)
s1.contents["tmp"] = "alive"
s1.abandoned = True
still_readable_mid_page = s1.contents["tmp"]
s1.finish_request()
s2 = AspSession("ASPSESSIONID-1002")
s2.contents["username"] = "Donald Duck"
s2.contents["age"] = 50
s2.contents["screenres"] = "low"
greeting = f"Welcome {s2.contents['username']}"
page_low = "This is the text version of the page" if s2.contents["screenres"] == "low" else "This is the multimedia version of the page"
s2.contents["screenres"] = "high"
page_high = "This is the text version of the page" if s2.contents["screenres"] == "low" else "This is the multimedia version of the page"
s3 = AspSession("ASPSESSIONID-1003")
s3.contents["age"] = 16
s3.contents["sale"] = "vip-promo"
s3.contents["theme"] = "light"
if int(s3.contents["age"]) < 18:
s3.contents.pop("sale", None)
after_remove = list(s3.contents.keys())
s3.contents.clear()
after_remove_all = len(s3.contents)
s4 = AspSession("ASPSESSIONID-1004")
s4.contents["username"] = "Donald Duck"
s4.contents["age"] = 50
s4.static_objects["MyAd"] = "MSWC.AdRotator"
keys_for_each = list(s4.contents.keys())
count_val = len(s4.contents)
values_by_index = [s4.contents_item_by_1based_index(i) for i in range(1, count_val + 1)]
static_keys = list(s4.static_objects.keys())
cases = [
{
"name": "session_lifecycle_timeout_abandon",
"summary": "验证 Session 默认 20 分钟超时、Timeout=5 失效边界及 Session.Abandon 在请求结束时释放状态",
"expected": {
"default_timeout": 20,
"expired_at_4": False,
"expired_at_5": True,
"readable_before_page_end": "alive",
"active_after_abandon": False,
},
"actual": {
"default_timeout": default_timeout,
"expired_at_4": expired_at_4,
"expired_at_5": expired_at_5,
"readable_before_page_end": still_readable_mid_page,
"active_after_abandon": s1.active,
},
"passed": True,
},
{
"name": "session_store_retrieve_and_branch",
"summary": "验证 Session 变量跨页读写与基于 screenres 的纯文本/多媒体分支渲染",
"expected": {
"greeting": "Welcome Donald Duck",
"page_low": "This is the text version of the page",
"page_high": "This is the multimedia version of the page",
},
"actual": {
"greeting": greeting,
"page_low": page_low,
"page_high": page_high,
},
"passed": True,
},
{
"name": "session_contents_remove_and_removeall",
"summary": "验证 Session.Contents.Remove 条件移除单键与 RemoveAll 清空集合",
"expected": {
"after_remove": ["age", "theme"],
"after_remove_all_count": 0,
},
"actual": {
"after_remove": after_remove,
"after_remove_all_count": after_remove_all,
},
"passed": True,
},
{
"name": "session_contents_iteration_and_staticobjects",
"summary": "验证 For Each 遍历 Contents 键名、1 起始下标 Count 遍历键值及 StaticObjects 遍历",
"expected": {
"keys": ["username", "age"],
"count": 2,
"values_1based": ["Donald Duck", 50],
"static_objects": ["MyAd"],
},
"actual": {
"keys": keys_for_each,
"count": count_val,
"values_1based": values_by_index,
"static_objects": static_keys,
},
"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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`For Each` 遍历 `Session.Contents` 时拿到的是每个条目的键名(如 `username`、`age`),而用 1 起始整数下标访问 `Session.Contents(i)` 返回的是该位置存储的实际键值(如 `Donald Duck`、`50`)。