C# webserver 可以通過使用內置的 HttpSessionState
類或自定義 Session 管理器來管理 Session。以下是兩種方法的示例:
HttpSessionState
類:using System.Web;
// 在請求處理方法中獲取 Session
public void HandleRequest(HttpContext context)
{
HttpSessionState session = context.Session;
// 設置 Session 變量
session["username"] = "John Doe";
// 獲取 Session 變量
string username = session["username"] as string;
}
using System;
using System.Collections.Generic;
public class SessionManager
{
private static Dictionary<string, Dictionary<string, object>> sessions = new Dictionary<string, Dictionary<string, object>>();
public static void SetSessionValue(string sessionId, string key, object value)
{
if (!sessions.ContainsKey(sessionId))
{
sessions[sessionId] = new Dictionary<string, object>();
}
sessions[sessionId][key] = value;
}
public static object GetSessionValue(string sessionId, string key)
{
if (sessions.ContainsKey(sessionId) && sessions[sessionId].ContainsKey(key))
{
return sessions[sessionId][key];
}
return null;
}
}
然后在請求處理方法中使用自定義 Session 管理器:
// 在請求處理方法中獲取 Session
public void HandleRequest(HttpContext context)
{
string sessionId = context.Request.Cookies["sessionId"].Value;
// 設置 Session 變量
SessionManager.SetSessionValue(sessionId, "username", "John Doe");
// 獲取 Session 變量
string username = SessionManager.GetSessionValue(sessionId, "username") as string;
}