【问题标题】:VB.NET: How to access a session variable from a public class?VB.NET:如何从公共类访问会话变量?
【发布时间】:2014-03-04 00:15:05
【问题描述】:

我正在开发一个 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 ,结果相同。)有什么想法吗?

谢谢!

大卫

【问题讨论】:

  • 您没有在参数中传递当前会话是否有原因?
  • 好吧,debugControl 的实例化需要被每个类中的每个方法写入(它是为了维护第一次失败的调试日志),所以它在每个函数调用上传递它似乎很多开销。

标签: vb.net class session public


【解决方案1】:

如果通过“与任何 .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

【讨论】:

  • 不,它不是网络服务。它只是 App_Code 目录中的 .vb 文件。无论如何我尝试了 webMethod,但遇到了一大堆不同的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
相关资源
最近更新 更多