ASP Session

Session 的集合与属性、Abandon、Timeout、LCID 与 CodePage。

Intermediate
Key PointsSession 有 Contents(变量)与 StaticObjects(对象),加 Timeout、CodePage、LCID 三个属性。

属性一览

MemberTypePurpose
SessionID只读唯一标识这个会话
Timeout读写无活动多少分钟失效
CodePage读写会话内字符串编码,中文用 65001
LCID读写日期、货币格式,简体中文 2052
Contents集合所有 Session("x")
StaticObjects集合<object runat=Server> 声明的对象
Abandon方法丢弃会话

CodePage 与 LCID

ASP
<%
    Session.CodePage = 65001        ' UTF-8
    Session.LCID = 2052             ' 简体中文

    Response.Write FormatCurrency(1234.5) & "<br>"
    Response.Write FormatDateTime(Now(), 1) & "<br>"
    Response.Write WeekdayName(Weekday(Now()))
%>
Output
¥1,234.50
2026年11月3日
星期二

With LCID = 2052, FormatCurrency uses the yuan symbol, FormatDateTime uses Chinese date order and WeekdayName returns Chinese names. The default is English formats.

Timeout

ASP
<%
    Session.Timeout = 5              ' 5 分钟无活动就失效

    Response.Write "剩余时间:" & Session.Timeout & " 分钟"
%>

The timeout counts from the last request, not from creation, so an active user never expires. Mobile apps often return after long gaps, and too short a timeout logs users out unexpectedly.

遍历与清理

ASP
<%
    Dim k
    For Each k In Session.Contents
        Response.Write k & " = " & Session(k) & "<br>"
    Next

    Response.Write "共 " & Session.Contents.Count & " 项<br>"

    Session.Contents.Remove("cart")
    Session.Contents.RemoveAll
%>

Abandon 的真实行为

ASP
<%
    Session("uid") = 42
    Session.Abandon
    Response.Write Session("uid")        ' 仍然输出 42
%>
Output
42

Abandon only marks the session for disposal; values remain readable on the current page and are actually destroyed after it finishes. Calling Abandon then Redirect is safe, but reading session values later on the same page returns stale data.

The session id lives in an ASPSESSIONID cookie. Clearing cookies starts a new session while the online count never decrements, because Session_OnEnd fires only on timeout or Abandon, never on cookie deletion.

常见误用

  • 把大对象放 Session —— 每个用户一份,几十个用户就把内存吃光
  • 在 Session 里存数据库连接 —— 连接数暴涨,且事务状态混乱
  • 依赖 Session 做权限 —— 会话劫持后权限全失,需配合 IP 校验或二次验证

Friends & Partners