VB.NET:如何从公共类访问会话变量?

时间:2014-02-06 20:24:46

标签: vb.net class session public

我正在开发一个ASP Web应用程序,它既包含代码隐藏页面,也包含与任何.asp页面无关的单独类。在代码隐藏页面中,我管理了几个不同的会话变量,其中一个是Session(“debug”)。例如:

    'Have we created a session debug variabe yet?  If not, create one!
    If Session("debug") IsNot Nothing Then
        _debug = TryCast(Session("debug"), DebugControl)
    Else
        _debug = New DebugControl
        Session("debug") = _debug
    End If
    'This is the debug control.  Uncomment this to turn debugging on
    _debug.isOn = True

在其中一个公共类中,我尝试在类构造函数中以编程方式使用会话变量:

    Public Class SQLControl
        Inherits System.Web.UI.MasterPage
            Private _debug As DebugControl

            Public Sub New()
                If HttpContext.Current.Session("debug") Is Nothing Then
                    _debug = New DebugControl
                    HttpContext.Current.Session("debug") = _debug
                Else
                    _debug = DirectCast(HttpContext.Current.Session("debug"), DebugControl)
                End If
            End Sub

但是,当我构建应用程序时,我得到以下内容(第26行突出显示为错误):

Server Error in '/dev' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 24: 
Line 25:     Public Sub New()
Line 26:         If HttpContext.Current.Session("debug") Is Nothing Then
Line 27:             _debug = New DebugControl
Line 28:             HttpContext.Current.Session("debug") = _debug

我已经阅读了几个描述类似问题的线程,但是大多数线程建议使用HttpContext.Current.Session()方法,我已经在做了(我也尝试过System.Web.HttpContext.Current.Session) ,结果相同。)有什么想法吗?

谢谢!

大卫

1 个答案:

答案 0 :(得分:0)

如果“与任何.asp [sic]页面没有关联的单独类”暗示它们包含WebService的方法,您可以告诉它require use of the session state带有装饰,例如

<WebMethod(EnableSession:=True)> _
 Public Function AddToBasket(ByVal filename As String) As String
    Return BasketController.AddItem(filename, HttpContext.Current).ToString
End Function