Skip to content

Session 管理详解

简介

cHttpServerSession 提供 HTTP 会话管理功能,支持三种存储方式:

  • 内存存储 (SessionStorageMemory) - 默认,进程内存储
  • 文件系统 (SessionStorageFileSystem) - 持久化到文件
  • 数据库存储 (SessionStorageDatabase) - 存储到数据库表

Session 存储类型配置

vb
Public Enum EnumSessionStorageType
    SessionStorageMemory = 0      ' 内存存储(不持久化)
    SessionStorageFileSystem = 1   ' 文件系统存储
    SessionStorageDatabase = 2     ' 数据库存储
End Enum

快速开始

1. 内存存储(默认)

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' 默认就是内存存储,无需配置
    Server.SessionStorageType = SessionStorageMemory
    
    Call Server.Start(8080)
End Sub

' 控制器中使用
Public Sub Login(ctx As cHttpServerContext)
    ' 登录成功后存储用户信息
    ctx.Session("user_id") = "123"
    ctx.Session("username") = "张三"
    ctx.Session.TimeOut = 30  ' 30分钟超时
    
    ctx.Response.Json Nothing, 0, "登录成功"
End Sub

Public Sub Profile(ctx As cHttpServerContext)
    ' 读取 Session
    Dim userId As String
    userId = ctx.Session("user_id")
    
    If userId = "" Then
        ctx.Response.State401 "未登录"
        Exit Sub
    End If
    
    Dim profile As New Scripting.Dictionary
    profile("user_id") = userId
    profile("username") = ctx.Session("username")
    
    ctx.Response.Json profile
End Sub

Public Sub Logout(ctx As cHttpServerContext)
    ' 清除 Session
    ctx.Session.Abandon
    ctx.Response.Json Nothing, 0, "退出成功"
End Sub

2. 文件系统存储

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' 配置文件存储
    Server.SessionStorageType = SessionStorageFileSystem
    Server.SessionStoragePath = "C:\MyApp\Sessions"  ' Session 文件保存目录
    Server.SessionCookieName = "MY_SESSIONID"         ' Cookie 名称
    
    Call Server.Start(8080)
End Sub

Session 文件格式(JSON):

json
{
  "SessionID": "550e8400-e29b-41d4-a716-446655440000",
  "CreatedAt": "2026-05-17 10:30:00",
  "LastAccessedAt": "2026-05-17 10:35:00",
  "Timeout": 20,
  "Data": {
    "user_id": "123",
    "username": "张三"
  }
}

3. 数据库存储

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' 配置数据库连接
    If Server.Database.Connect(enumDbType.Mysql, "localhost,3306", "root", "password", "mydb") Then
        ' 配置数据库 Session 存储
        Server.SessionStorageType = SessionStorageDatabase
        Server.SessionStoragePath = "user_sessions"  ' 表名
        Server.SessionCookieName = "SESSION_ID"
        
        Call Server.Start(8080)
    End If
End Sub

数据库表结构

sql
CREATE TABLE user_sessions (
    SessionID VARCHAR(255) PRIMARY KEY,
    SessionData TEXT,
    CreatedAt DATETIME,
    LastAccessedAt DATETIME,
    ExpiresAt DATETIME,
    INDEX idx_expires (ExpiresAt)
);

Session 属性详解

Item (默认属性)

获取或设置 Session 数据。

vb
' 存储数据
ctx.Session("key") = "value"
ctx.Session("user") = userObject  ' 支持对象

' 读取数据
Dim value As Variant
value = ctx.Session("key")

' 检查存在性
If ctx.Session.Exists("key") Then
    ' ...
End If

SessionID

获取 Session ID。

vb
Debug.Print "Session ID: " & ctx.Session.SessionID
' 输出: 550e8400-e29b-41d4-a716-446655440000

TimeOut

超时时间(分钟),默认 20 分钟。

vb
' 设置 60 分钟超时
ctx.Session.TimeOut = 60

' 0 表示永不过期
ctx.Session.TimeOut = 0

CreatedAt

创建时间。

vb
Debug.Print "创建时间: " & ctx.Session.CreatedAt

LastAccessedAt

最后访问时间。

vb
Debug.Print "最后访问: " & ctx.Session.LastAccessedAt

Session 方法详解

Exists

检查键是否存在。

vb
If ctx.Session.Exists("user_id") Then
    ' 用户已登录
Else
    ' 未登录
End If

Remove

删除指定键。

vb
' 删除单个键
ctx.Session.Remove("temp_data")

Clear

清空所有数据(保留 SessionID)。

vb
ctx.Session.Clear

Abandon

放弃当前 Session(清空数据并生成新 SessionID)。

vb
' 退出登录时使用
ctx.Session.Abandon

IsExpired

检查 Session 是否已过期。

vb
If ctx.Session.IsExpired Then
    ctx.Response.State401 "Session 已过期"
End If

Touch

更新最后访问时间。

vb
' 手动刷新 Session 时间
ctx.Session.Touch

完整登录示例

vb
' cAuthController.cls

' POST /login
Public Sub Login(ctx As cHttpServerContext)
    Dim username As String, password As String
    username = ctx.Request.Form("username")
    password = ctx.Request.Form("password")
    
    ' 验证账号密码
    If Not ValidateUser(username, password) Then
        ctx.Response.Json Nothing, 1, "用户名或密码错误"
        Exit Sub
    End If
    
    ' 获取用户信息
    Dim user As Scripting.Dictionary
    Set user = GetUserInfo(username)
    
    ' 存储到 Session
    ctx.Session("user_id") = user("id")
    ctx.Session("username") = user("username")
    ctx.Session("role") = user("role")
    ctx.Session.TimeOut = 120  ' 2小时
    
    ' 返回用户信息
    ctx.Response.Json user, 0, "登录成功"
End Sub

' GET /logout
Public Sub Logout(ctx As cHttpServerContext)
    ctx.Session.Abandon
    ctx.Response.Json Nothing, 0, "退出成功"
End Sub

' GET /profile
Public Sub Profile(ctx As cHttpServerContext)
    ' 检查登录状态
    If Not ctx.Session.Exists("user_id") Then
        ctx.Response.State401 "请先登录"
        Exit Sub
    End If
    
    ' 返回用户信息
    Dim profile As New Scripting.Dictionary
    profile("user_id") = ctx.Session("user_id")
    profile("username") = ctx.Session("username")
    profile("role") = ctx.Session("role")
    
    ctx.Response.Json profile
End Sub

' 辅助函数
Private Function ValidateUser(username As String, password As String) As Boolean
    ' 验证逻辑...
    ValidateUser = True
End Function

Private Function GetUserInfo(username As String) As Scripting.Dictionary
    Dim user As New Scripting.Dictionary
    user("id") = "123"
    user("username") = username
    user("role") = "admin"
    Set GetUserInfo = user
End Function

Session 安全建议

  1. 使用 HttpOnly Cookie:防止 XSS 攻击
  2. 设置合理超时时间:不要过长
  3. 使用 HTTPS:防止 Session ID 被截获
  4. 定期清理过期 Session:文件/数据库存储需要清理任务
  5. 敏感数据加密:不要在 Session 中存储明文密码
vb
' 安全配置示例
' 1. 设置 Cookie HttpOnly
With ctx.Cookies.Cookie("SESSIONID")
    .HttpOnly = True
    .Secure = True  ' HTTPS 下使用
    .SameSite = "Strict"
End With

' 2. Session 超时设置
ctx.Session.TimeOut = 20  ' 20分钟

最后更新: 2026-05-17

VB6及其LOGO版权为微软公司所有