ASP Session
Session 对象、会话 ID、超时、Abandon 与常见误用。
Key PointsSession 是每个用户一份的服务端存储,靠 ASPSESSIONID Cookie 关联,默认 20 分钟无活动就失效。
存与取
ASP
<%
' 存
Session("uid") = 42
Session("userName") = "Ada"
Session("cart") = Array("book", "pen")
' 取
Response.Write Session("userName") & "<br>"
Response.Write Session("uid") + 1 & "<br>"
' 判断存在
If IsEmpty(Session("uid")) Then
Response.Write "未登录"
End If
' 删单个
Session.Contents.Remove("cart")
%>Output
Ada
43A missing Session("x") is Empty; test with IsEmpty. If Session("uid") = "" often works but is loose for numeric session values.
会话信息
ASP
<%
Response.Write "会话 ID:" & Session.SessionID & "<br>"
Response.Write "超时(分钟):" & Session.Timeout & "<br>"
Response.Write "会话数:" & Session.Contents.Count & "<br>"
Session.Timeout = 60 ' 改成 60 分钟
%>Output
会话 ID:842193057
超时(分钟):20
会话数:3结束会话
ASP
<%
Session.Abandon ' 销毁会话(在当前页执行完后生效)
Response.Redirect "login.asp"
%>Abandon does not destroy immediately; it marks the session for disposal when the page finishes. Values remain readable later on the same page, which makes it look like a no-op.
会话配置
Text
IIS 管理器 → 网站 → ASP → 会话属性
☑ 启用会话状态
会话超时:20 分钟
☐ 启用无 Cookie 会话 ← 开启后会话 ID 会出现在 URL 里Disabling session state saves IIS a per-user memory structure; pages that are purely static or read-only can do without it. Once disabled, touching Session raises an error.
Sessions live in the IIS process memory and vanish on app-pool recycle or reboot, and are not shared across servers. Surviving restarts or load balancing needs a state service or database — classic ASP is weak here.
Session 与 Cookie 的选择
| Cookie | ||
|---|---|---|
| Where | 服务端 | 客户端 |
| Security | 较高,用户改不了 | 低,明文可改 |
| Capacity | 受服务器内存限制 | 4KB |
| Lifetime | 默认 20 分钟 | 可设很长 |
存与取
ASP
<%
' 存
Session("uid") = 42
Session("userName") = "Ada"
Session("cart") = Array("book", "pen")
' 取
Response.Write Session("userName") & "<br>"
Response.Write Session("uid") + 1 & "<br>"
' 判断存在
If IsEmpty(Session("uid")) Then
Response.Write "未登录"
End If
' 删单个
Session.Contents.Remove("cart")
%>Output
Ada
43Session("x") 不存在时是 Empty,用 IsEmpty 判断。直接 If Session("uid") = "" 也能用,但对数字类型的会话值不够严谨。
会话信息
ASP
<%
Response.Write "会话 ID:" & Session.SessionID & "<br>"
Response.Write "超时(分钟):" & Session.Timeout & "<br>"
Response.Write "会话数:" & Session.Contents.Count & "<br>"
Session.Timeout = 60 ' 改成 60 分钟
%>Output
会话 ID:842193057
超时(分钟):20
会话数:3结束会话
ASP
<%
Session.Abandon ' 销毁会话(在当前页执行完后生效)
Response.Redirect "login.asp"
%>Abandon 不是立刻销毁,而是把会话标记为「本页处理完就丢弃」。所以同一页里 Abandon 之后仍然能读到旧值——这一点常让人以为它没生效。
会话配置
Text
IIS 管理器 → 网站 → ASP → 会话属性
☑ 启用会话状态
会话超时:20 分钟
☐ 启用无 Cookie 会话 ← 开启后会话 ID 会出现在 URL 里关掉会话状态能让 IIS 少维护一份内存,纯静态或纯查询的页面可以关。但一旦关了,Session 对象就用不了,访问会直接报错。
Session 存在 IIS 进程内存里,应用池回收或服务器重启就全丢,多台服务器之间也不共享。要跨重启、做负载均衡,得配 ASP.NET State Service 或数据库存储——经典 ASP 在这方面支持很弱。
Session 与 Cookie 的选择
| Session | Cookie | |
|---|---|---|
| 存放位置 | 服务端 | 客户端 |
| 安全性 | 较高,用户改不了 | 低,明文可改 |
| 容量 | 受服务器内存限制 | 4KB |
| 寿命 | 默认 20 分钟 | 可设很长 |