开发者

Manually create/populate .NET Session object

First a brief background. I am using .NET output caching and substitution controls to keep a few bits updated on each page refresh. The static methods that the substitution controls use require access to the Session object. Unfortunately, the HttpContext session is null in those methods.

I'm not going to rewrite my app to use a different store than the Session. Se开发者_运维百科ssion is perfect for everything I need except this one aspect.

Can I manually create or populate a session object or otherwise get at its data by some sort of black magic wizardry? The session cookie is still being set from the client to the server. The info has got to be there somewhere. How do I get at it?


I'm not convinced this is a "good" way to go...but you can very dodgily store a reference to the Session in a shared/static variable and access it then.

Public Class SessionHelper

    Public Shared TheSession As HttpSessionState

End Class

In your Session Start event (haven't figured out the best place to put it yet as the session isn't available in Application start as far as I am aware)

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)

    ' Store a reference...only do this once etc etc
    If SessionHelper.TheSession Is Nothing Then
        SessionHelper.TheSession = HttpContext.Current.Session
    End If

End Sub

Then in your code you can just reference the helper

Dim someVariable as String = SessionHelper.TheSession.Item("ItemName")

A few things I'm not sure about this method:

  • not sure if the session object is now not thread safe
  • it doesn't seem quite right
  • this example is extremely simple...

Edit
I verified this worked for me by adding something to the cache and seeing if the session was available in the Cache Remove Callback which Http.Context.Current is not available in.

Edit 2
Here's a screenshot of it correctly returning the value. So it must be working to some degree, but the fact that the SessionId is not set is kind of worrying...I know I've used this technique before to access the Cache object but the cache is the cache, where as the session does need something to identify each session...Here you go anyway:

Manually create/populate .NET Session object


Session information is stored in the server's memory. You can, however, configure ASP.NET to store the session information inside SQL Server.


HttpContext.Current.Session should give you access to the current Session. The only time when this would not work is when there is no current HttpContext. As long as you have a reference to System.Web, it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜