代码之家  ›  专栏  ›  技术社区  ›  Mike Ruhlin

强制在.NET中创建httpcontext.current.session

  •  2
  • Mike Ruhlin  · 技术社区  · 15 年前

    我正在开发一个应用程序,它使用.NET的StaticFileHandler提供动态生成的内容… 我们的应用程序还有另一部分使用当前的httpsession来存储用户特定的数据。

    由于StaticFileHandler是为处理静态文件而设计的,因此它不实现IRequiresSessionState,因此通过应用程序的该部分的任何内容都无法访问来自应用程序其余部分的会话特定数据。

    StaticFileHandler是System.Web的内部处理程序,因此我不能将其扩展到自己的类中,该类还实现IRequiressessionState。当检测到会话为空时,是否还有其他方法可以强制创建会话?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Mike Ruhlin    15 年前

    我们还有一个自定义会话提供程序,它使用了一些更高效的缓存,所以我可以利用它自己创建会话。如果有其他人感兴趣,这里是我的代码,但请注意,如果您想借用,您必须自己对其进行调整:

     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,即使我实际上只在非常罕见的情况下使用会话。

    推荐文章