views:

32

answers:

3

This is an ASP.NET 2010 web app written in vb. I use several Session variables. I want to pass them all to a central class and let the class manage them. However, I am having some trouble.

Here is the code on the calling page:

Dim arrGoodSessions() As String ={"nameofsession1", "nameofsession2", "nameofsession3"}
Utilities.ManageSessionVariables(arrGoodSessions)

It calls that static Utilties class. I have set a reference to System.Web. Here is the code in the class:

Imports System.Web
Imports System.Web.SessionState
Imports System.Web.SessionState.HttpSessionState
Imports System.Web.HttpContext


Public Class Utilities : Implements IRequiresSessionState
    Public Shared Sub ManageSessionVariables(ByVal arrGoodSessions As String())
        Dim alItemsToBeRemoved As New ArrayList

        For Each Item In Session.Contents
            If arrGoodSessions.Contains(Item.ToString) = False Then
                alItemsToBeRemoved.Add(Item.ToString)
            End If
        Next
        For Each i As String In alItemsToBeRemoved
            Session.Contents.Remove(i)
        Next
    End Sub
End Class

This attempts to simply read in some names of session variables and then cycle through all session variables and remove any I didn't list. This works when all of the cod eis on the page. But when I move this to the class, it doesn't recgonize Session.Contents.

+3  A: 

I think you need to reference HttpContext.Current.Session

David
+1  A: 

You can access all of the ASP.NET objects such as Session, Request, Response, etc. by referencing them through HttpContext.Current in System.Web, like so:

For Each Item In HttpContext.Current.Session.Contents
    If arrGoodSessions.Contains(Item.ToString) = False Then
        alItemsToBeRemoved.Add(Item.ToString)
    End If
Next

Keep in mind you'll need to add a reference to System.Web if the class is in a class library project, and also keep in mind that this makes the code in question unusable outside of an HTTP context. You might want to consider passing in the session contents as a parameter to the method to keep your code testable and reusable.

Ryan Brunner
A: 

One thing you could do is pass HttpContext.Current as a parameter where you need it in your class, something like this

Public Shared Sub ManageSessionVariables(ByVal arrGoodSessions As String(), ByVal context as HttpContext)

End Sub

And now within ManageSessionVariables you have access to the current HttpContext

PsychoCoder