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;
}