【问题标题】:Forcing creation of HttpContext.Current.Session in .NET强制在 .NET 中创建 HttpContext.Current.Session
【发布时间】:2010-09-24 03:53:56
【问题描述】:

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

由于 StaticFileHandler 旨在处理静态文件,因此它没有实现 IRequiresSessionState,因此通过该应用程序部分的任何内容都无法从应用程序的其余部分访问特定于会话的数据。

StaticFileHandler 是 System.Web 内部的,所以我不能将它扩展到我自己的也实现 IRequiresSessionState 的类中。当我检测到它为空时,是否有其他方法可以强制创建会话?

【问题讨论】:

    标签: .net httpsession


    【解决方案1】:

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

     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,即使我实际上只是在极少数情况下使用会话。

    【讨论】:

    • +1:一直在寻找这样的东西,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2011-11-28
    • 2012-08-13
    相关资源
    最近更新 更多