cHttpServerContext Context Object
Overview
cHttpServerContext is the core object of the HttpServer framework, spanning the entire request lifecycle. It encapsulates all information and functionality needed for HTTP request processing, serving as the carrier for data transfer between middleware and controllers.
Context in Request Lifecycle:
Request Arrive
│
▼
┌─────────────────────────────────────────────────────────────┐
│ cHttpServerContext │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Request │ │ Session │ │ Response │ │
│ │ (Request) │ │ (Session) │ │ (Response) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Cookies │ │ Db │ │ Client │ │
│ │ (Cookies) │ │ (Database) │ │ (Client) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ SSE │ │ UserData │ (Custom Data Pass) │
│ │ (Push) │ │(Extension) │ │
│ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
Middleware -> Controller -> ResponseCore Properties
Request - Request Object
Contains all request information sent by the client.
Public Request As cHttpServerRequestCommon Usage:
' Get request method
Dim method As String
method = ctx.Request.MethodName ' "GET" / "POST" / "PUT" / "DELETE"
' Get request path
Dim path As String
path = ctx.Request.PathInfo ' "/user/list"
' Get query parameters
Dim page As String
page = ctx.Request.QueryString("page")
' Get form data
Dim username As String
username = ctx.Request.Form("username")
' Get JSON data
Dim name As String
name = ctx.Request.Json.GetItem("name")
' Smart get (auto search Query/Form/Json)
Dim value As Variant
value = ctx.Request("keyword")
' Get request headers
Dim token As String
token = ctx.Request.Header("Authorization")Response - Response Object
Used to build and send HTTP responses.
Public Response As cHttpServerResponseCommon Methods:
' Return text
ctx.Response.Text "Hello World"
' Return HTML
ctx.Response.Html "<h1>Title</h1>"
' Return JSON
ctx.Response.Json data, 0, "Success"
' Return file
ctx.Response.File "/path/to/file.pdf"
' Return error status
ctx.Response.State404 "Page not found"
ctx.Response.State500 "Internal server error"
ctx.Response.State401 "Unauthorized"Session - Session Object
Manages user session data, supporting memory, file, and database storage.
Public Session As cHttpServerSessionCommon Operations:
' Store data
ctx.Session("user_id") = "123"
ctx.Session("username") = "John"
' Read data
Dim userId As String
userId = ctx.Session("user_id")
' Check existence
If ctx.Session.Exists("user_id") Then
' User is logged in
End If
' Set timeout (minutes)
ctx.Session.TimeOut = 60
' Remove data
ctx.Session.Remove("temp_data")
' Clear session
ctx.Session.Clear
' Abandon session (logout)
ctx.Session.AbandonLogin Verification Example:
Public Sub CheckLogin(ctx As cHttpServerContext)
If Not ctx.Session.Exists("user_id") Then
ctx.Response.State401 "Please login first"
ctx.Abort ' Stop subsequent processing
End If
End SubCookies - Cookie Object
Manages cookies in requests and responses.
Public Cookies As cHttpServerCookiesReading Request Cookies:
If ctx.Cookies.Exists("remember") Then
Dim token As String
token = ctx.Cookies.Cookie("remember").Value
End IfSetting Response Cookies:
With ctx.Cookies.Cookie("session_id")
.Value = GenerateToken()
.Expires = DateAdd("h", 2, Now)
.HttpOnly = True
.Secure = True
.Path = "/"
.SameSite = "Strict"
End WithDb - Database Object
Provides database access capability.
Public Db As cDataBaseQuery Examples:
' Simple query
If ctx.Db.Sql("SELECT * FROM users WHERE id=?") _
.Param("id", userId, adVarChar) _
.Fetch Then
Dim user As Scripting.Dictionary
Set user = ctx.Db.Rows(1)
End If
' Insert data
ctx.Db.Sql("INSERT INTO logs (action, time) VALUES (?, NOW())") _
.Param("action", "login", adVarChar) _
.ExecParam
' Transaction processing
ctx.Db.TransBegin
' ... Execute multiple SQL ...
ctx.Db.TransCommitClientInfo - Client Information
Contains information about the connected client.
Public ClientInfo As cHttpServerClientInfoProperties:
Dim ip As String
ip = ctx.ClientInfo.IP ' "192.168.1.100"
Dim port As Long
port = ctx.ClientInfo.Port ' 52341
Dim hSocket As Long
hSocket = ctx.ClientInfo.hSocket ' Socket handle
Dim connectTime As Date
connectTime = ctx.ClientInfo.ConnectAtUse Cases:
' IP blacklist check
Public Sub CheckIP(ctx As cHttpServerContext)
Dim blacklist As Variant
blacklist = Array("192.168.1.100", "10.0.0.50")
If InArray(ctx.ClientInfo.IP, blacklist) Then
ctx.Response.State403 "IP has been blocked"
ctx.Abort
End If
End Sub
' Log access
Public Sub LogAccess(ctx As cHttpServerContext)
Dim log As String
log = Now & " | " & ctx.ClientInfo.IP & " | " & ctx.Request.PathInfo
Call WriteLog(log)
End SubServer - Server Configuration
Access server configuration information.
Public Server As cHttpServerSvrProperties:
Dim webRoot As String
webRoot = ctx.Server.WebRoot ' "C:\WebRoot"
Dim port As Long
port = ctx.Server.Port ' 8080
Dim ip As String
ip = ctx.Server.IP ' "0.0.0.0"Check Static Files:
If ctx.Server.IsStaticFile("/image/logo.png") Then
ctx.Response.File "/image/logo.png"
End IfSSE - Real-time Push
Server-Sent Events real-time push object.
Public SSE As New cSSEContextUsage Example:
' Send message to specific client
Call ctx.SSE.Send(ctx.ClientInfo.hSocket, "event", "data", "id")
' Broadcast to all clients
Call ctx.SSE.Broadcast("notification", "System announcement")
' Check connection status
If ctx.SSE.IsConnected(ctx.ClientInfo.hSocket) Then
' Client is online
End IfTimeUse - Performance Statistics
Used to track request processing time.
Public TimeUse As New cTimeUseUsage Example:
Public Sub SlowOperation(ctx As cHttpServerContext)
ctx.TimeUse.Start
' ... Perform time-consuming operation ...
Sleep 2000
ctx.TimeUse.End_
Debug.Print "Operation time: " & ctx.TimeUse.Elapsed & " ms"
' Output: Operation time: 2000 ms
End SubUserData - User Data Storage
Used to pass custom data within the request lifecycle.
Public UserData As New Scripting.DictionaryPassing Data Between Middleware and Controller:
' === In Middleware ===
Public Sub AuthMiddleware(ctx As cHttpServerContext)
' After validating Token, store user info
ctx.UserData("user_id") = "123"
ctx.UserData("username") = "John"
ctx.UserData("role") = "admin"
End Sub
' === In Controller ===
Public Sub GetData(ctx As cHttpServerContext)
' Get data set by middleware
Dim userId As String
userId = ctx.UserData("user_id")
' Return different data based on role
If ctx.UserData("role") = "admin" Then
' Return full data
Else
' Return partial data
End If
End SubControl Methods
Abort - Terminate Request
Terminates all subsequent processing (middleware, controller).
Public Sub Abort()Example:
Public Sub CheckAuth(ctx As cHttpServerContext)
If Not IsValidToken(ctx) Then
ctx.Response.State401 "Unauthorized"
ctx.Abort ' Stop subsequent processing
End If
End SubSkipNextMiddleWare - Skip Subsequent Middleware
Skips remaining middleware, goes directly to controller.
Public Sub SkipNextMiddleWare()Example:
Public Sub CacheMiddleware(ctx As cHttpServerContext)
' Check cache hit
If CacheExists(ctx.Request.PathInfo) Then
ctx.Response.Text GetCache(ctx.Request.PathInfo)
ctx.SkipNextMiddleWare ' Skip other middleware
End If
End SubComplete Request Handling Example
' cOrderController.cls
Option Explicit
' GET /api/orders
Public Sub List(ctx As cHttpServerContext)
' 1. Start performance tracking
ctx.TimeUse.Start
' 2. Permission check (data from middleware)
Dim userId As String
userId = ctx.UserData("user_id")
If userId = "" Then
ctx.Response.State401 "Please login first"
ctx.Abort
Exit Sub
End If
' 3. Get request parameters
Dim page As Long, limit As Long
page = CLng(ctx.Request.QueryString("page"))
limit = CLng(ctx.Request.QueryString("limit"))
' 4. Database query
Dim sql As String
sql = "SELECT * FROM orders WHERE user_id=? ORDER BY created_at DESC LIMIT ?,?"
If Not ctx.Db.Sql(sql) _
.Param("user_id", userId, adVarChar) _
.Param("offset", (page - 1) * limit, adInteger) _
.Param("limit", limit, adInteger) _
.Fetch Then
ctx.Response.State500 "Query failed"
Exit Sub
End If
' 5. Build response
Dim result As New Scripting.Dictionary
result("items") = ctx.Db.Rows
result("page") = page
result("total") = ctx.Db.Count("orders WHERE user_id='" & userId & "'")
ctx.Response.Json result, 0, "Success"
' 6. Log access
Call WriteLog(ctx.ClientInfo.IP & " queried order list")
' 7. End performance tracking
ctx.TimeUse.End_
Debug.Print "Request processing time: " & ctx.TimeUse.Elapsed & "ms"
End Sub
' POST /api/orders
Public Sub Create(ctx As cHttpServerContext)
' 1. Get current user
Dim userId As String
userId = ctx.UserData("user_id")
' 2. Get request data
Dim productId As String, quantity As Long
productId = ctx.Request.Json.GetItem("product_id")
quantity = ctx.Request.Json.GetItem("quantity")
' 3. Start transaction
If Not ctx.Db.TransBegin Then
ctx.Response.State500 "System error"
Exit Sub
End If
On Error GoTo Rollback
' 4. Check stock
Dim stock As Long
stock = GetProductStock(ctx.Db, productId)
If stock < quantity Then
ctx.Response.Json Nothing, 1, "Insufficient stock"
GoTo Rollback
End If
' 5. Create order
Dim orderId As String
orderId = GenerateOrderId()
ctx.Db.Sql("INSERT INTO orders (id, user_id, product_id, quantity) VALUES (?, ?, ?, ?)") _
.Param("id", orderId, adVarChar) _
.Param("user_id", userId, adVarChar) _
.Param("product_id", productId, adVarChar) _
.Param("quantity", quantity, adInteger) _
.ExecParam
' 6. Deduct stock
ctx.Db.Sql("UPDATE products SET stock = stock - ? WHERE id = ?") _
.Param("quantity", quantity, adInteger) _
.Param("product_id", productId, adVarChar) _
.ExecParam
' 7. Commit transaction
ctx.Db.TransCommit
' 8. Return result
Dim result As New Scripting.Dictionary
result("order_id") = orderId
ctx.Response.Json result, 0, "Order created successfully"
' 9. Send real-time notification
Call ctx.SSE.Send(ctx.ClientInfo.hSocket, "order_created", _
"{\"order_id\":\"" & orderId & "\"}")
Exit Sub
Rollback:
ctx.Db.TransRollback
End SubContext Lifecycle
┌────────────────────────────────────────────────────────────────┐
│ Request Start │
│ Create Context Object │
└────────────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────┐
│ 1. Parse Request │
│ - Fill ctx.Request with data │
│ - Fill ctx.ClientInfo with client information │
│ - Parse request Cookies to ctx.Cookies │
│ - Load session data to ctx.Session │
└────────────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────┐
│ 2. Execute Pre-Middleware (can read/write ctx.UserData) │
│ - Middleware can access and modify all Context properties │
│ - Can call ctx.Abort to terminate request │
│ - Can call ctx.SkipNextMiddleWare to skip remaining │
│ - Can pass data to subsequent flow via ctx.UserData("key") │
└────────────────────────────────────────────────────────────────┘
│ ctx.UserData passes down
▼
┌────────────────────────────────────────────────────────────────┐
│ 3. Execute Controller (can read/write ctx.UserData) │
│ - Read ctx.Request to get request data │
│ - Use ctx.Db to operate database │
│ - Operate ctx.Session to manage sessions │
│ - Set ctx.Cookies to write response cookies │
│ - Call ctx.Response to send response │
│ - Use ctx.SSE to send real-time messages if needed │
│ - Read ctx.UserData to get data from middleware │
│ - Pass data to post-processing via ctx.UserData │
└────────────────────────────────────────────────────────────────┘
│ ctx.UserData passes down
▼
┌────────────────────────────────────────────────────────────────┐
│ 4. Execute Post-Processing (can read ctx.UserData) │
│ - Save ctx.Session to persistent storage │
│ - Send response cookies │
│ - Execute post-middleware │
│ - Read ctx.UserData for logging, statistics, etc. │
└────────────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────┐
│ Request End │
│ Release Context Object │
└────────────────────────────────────────────────────────────────┘Last Updated: 2026-05-17