我们还有一个自定义会话提供程序,它使用了一些更高效的缓存,所以我可以利用它自己创建会话。如果有其他人感兴趣,这里是我的代码,但请注意,如果您想借用,您必须自己对其进行调整:
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 Reflector查找如何访问它。
另外,这样做的一个缺点是,sessionstatemodule只在会话实际更改后创建cookie。然而,通过这段代码,我不得不一直创建cookie,即使我实际上只在非常罕见的情况下使用会话。