ASP Session

Session 对象、会话 ID、超时、Abandon 与常见误用。

Beginner
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
43

A 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 分钟可设很长

Friends & Partners