2014-02-06 44 views
0

我正在開發一個ASP Web應用程序,該應用程序既有代碼隱藏頁面又有不與任何.asp頁面關聯的單獨類。在代碼隱藏頁面中,我管理幾個不同的會話變量,其中一個是Session(「調試」)。例如:VB.NET:如何從公共類訪問會話變量?

'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,結果相同。)有什麼想法?

謝謝!

大衛

+0

有沒有原因你不通過參數當前會話? –

+0

那麼,debugControl的實例化需要被每個類中的每個方法寫入(它用於維護第一次失敗的調試日誌),所以它在每個函數調用中傳遞它似乎是一個很大的開銷。 – dtbritt

回答

0

如果「單獨的類不具有任何的.asp [原文]頁相關的」可暗示它們包含一個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 
+0

不,它不是網絡服務。這只是App_Code目錄中的.vb文件。無論如何,我嘗試過webMethod,但遇到了許多不同的問題。 – dtbritt