我们还有一个自定义会话提供程序,它使用了一些更有效的缓存,所以我能够利用它自己创建会话。如果其他人有兴趣,这是我的代码,但请注意,如果你想借用,你必须自己调整它:
public void EnsureSessionExists(HttpContext context) {
if (context.Session != null) {
// Hey, we've already got a session. That was easy...
return;
}
bool isNew = false;
string sesId = _sessionIdManager.GetSessionID(context);
if (String.IsNullOrEmpty(sesId)) {
// if ID is null or empty, it means we're creating a new session?
sesId = _sessionIdManager.CreateSessionID(context);
}
SessionStateStoreData data = GetSessionDataStore(context, sesId);
if (data == null) {
isNew = true;
data = CreateNewStoreData(context, _sessionTimeout);
// Create doesn't put it in the cache. This does.
SetSessionDataStore(context, sesId, data);
}
HttpSessionStateContainer container = new HttpSessionStateContainer(sesId, data.Items, data.StaticObjects, data.Timeout, isNew, HttpCookieMode.UseCookies, SessionStateMode.Custom, false);
SessionStateUtility.AddHttpSessionStateToContext(context, container);
// Force the cookie to get set here. SessionStateModule only sets it if the Handler has IRequiresSessionState
HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", _sessionIdManager.Encode(sesId));
cookie.Expires = DateTime.MinValue; // DateTime.MinValue makes it a session cookie.
context.Response.Cookies.Add(cookie);
}
最大的难题是关于获取 SessionStateStoreData 对象的部分。如果您使用的是默认实现,请通过 .NET 反射器了解如何访问它!
此外,这样做的一个缺点是 SessionStateModule 仅在会话实际更改后才创建一个 cookie。然而,通过这段代码,我不得不一直创建 cookie,即使我实际上只在极少数情况下使用会话。