简体   繁体   中英

ASP.Net Sessions in VB.Net

I have created a public property on my ASP.Net which holds a session of an entity. The purpose of which is that the entity is added to as the user fills in a number of steps on a form and then the whole lot is then saved to the database. However, when I go to use the session I am getting the error "object reference not set to an instance of an object".

Here is my code:

Public ReadOnly BreadQuestionnaire as Bread 
                          Implements IQuestionnaire.BreadQuestionnaire
       Get
           If Me.Session("BreadQuestionnaire") Is Nothing Then
              Me.Session("BreadQuestionnaire") = New Bread()
           End If
       Return TryCast(Me.Session("BreadQuestionnaire"),Bread)
      End Get
End Property

It is based upon code that I used in C# which has never given me any trouble before, but I have had VB.Net thrusted on me.

So, can anyone help me?

system.web.httpcontext.current.session.add("BreadQuestionnaire", Bread)

I'm not certain me.session will work - does the property belong to the page class or is it in it's own? Either way using httpcontext.current should always be available.

And you're retrieving the session twice, you could do it in one trip:

Public ReadOnly BreadQuestionnaire as Bread 
                          Implements IQuestionnaire.BreadQuestionnaire
       Get
           Dim _sessionBread = system.web.httpcontext.current.session("BreadQuestionnaire")
           If_sessionBread Is Nothing Then
             Dim _bread As New Bread
             system.web.httpcontext.current.session.add("BreadQuestionnaire", _bread)
             Return _bread
           Else
           Return _sessionBread
           End If
      End Get
End Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM