locked
Read session value from class RRS feed

  • Question

  • User746671234 posted
    Hello I have to read session value from class but it shows null reference error. Can anyone suggest me how to get session value there
    Monday, April 8, 2019 11:01 AM

Answers

  • User475983607 posted

    ravininave

    1] I think session has started on form load.

    2] after I load the form I get an error so it goes to global.asax then why I am not getting session variable here.

    3] I am using msgbox on locally just to test the value

    Again, we need code that actually runs and compiles to reproduce this issue.  There is no indication how or when the exception is fired. Perhaps you are firing the exception right after setting Session and that is why Session is not working as expected.

    I made a very simple test and cannot reproduce this issue.  Session is clearly displayed in the Visual Studio Console.

    Public Class CommonClass
        Public Sub SendMail(ByVal i_oErr As Exception, ByVal ClientIp As String, ByVal MyName As String)
            System.Diagnostics.Debug.WriteLine("Error Message: " & i_oErr.Message)
            System.Diagnostics.Debug.WriteLine("ClientIp: " & ClientIp)
            System.Diagnostics.Debug.WriteLine("MyName: " & MyName)
        End Sub
    End Class
        Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    
            Dim lastError As Exception = Server.GetLastError()
            If (lastError IsNot Nothing AndAlso lastError.Message <> "File does not exist.") AndAlso (lastError.Message <> "Thread was being aborted") AndAlso (lastError.Message <> "The client disconnected.") Then
                Dim xCl As New CommonClass
                xCl.SendMail(lastError, "127.0.0.1", System.Web.HttpContext.Current.Session("MyName"))
            End If
    
        End Sub
    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ExceptionSessionTest.aspx.vb" Inherits="VbWebApplication.ExceptionSessionTest" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            </div>
        </form>
    </body>
    </html>
    
    Public Class ExceptionSessionTest
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                Session("MyName") = "ravikant"
            End If
        End Sub
    
        Protected Sub Button1_Click(sender As Object, e As EventArgs)
            Throw New Exception("This is a test!")
        End Sub
    End Class

    Results

    Exception thrown: 'System.Exception' in VbWebApplication.dll
    An exception of type 'System.Exception' occurred in VbWebApplication.dll but was not handled in user code
    This is a test!
    
    Error Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
    ClientIp: 127.0.0.1
    MyName: ravikant
    The thread 0x24fc has exited with code 0 (0x0).
    The thread 0x6dd8 has exited with code 0 (0x0).

    However, I still feel that you exception handling is very fragile and need to rethinking the design.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 8, 2019 8:59 PM

All replies

  • User753101303 posted

    Hi,

    You mean you are using System.Web.HttpContext.Current.Session and it fails? Check if the problem is with Current or Session. It can depend on where you are trying to use that (for example you don't have an current http request when the application starts or the session ends). Or it could be perhaps some kind of design flaw that causes the session variable you are reading to be null.

    My personal preference is to hide session variables behind a facade so that I can load the value on demand.

    Monday, April 8, 2019 11:06 AM
  • User746671234 posted
    No even using simple session also not working in class. Actually this is error handler and when I got some error on site it sends me a mail. In mail I need to log the user I'd of user. I created error by entering wrong page address and session exists at this time
    Monday, April 8, 2019 11:49 AM
  • User475983607 posted

    ravininave

    No even using simple session also not working in class. Actually this is error handler and when I got some error on site it sends me a mail. In mail I need to log the user I'd of user. I created error by entering wrong page address and session exists at this time

    Session might not exist for many reasons.  However, using Session in a separate class is never recommended.  Always pass the Session value to the class either in a constructor, method, or property. 

    There is no guarantee that session will exist and you should always be able to fetch the Session values.  If you cannot then you have a design issue. 

    The only time you should see Session in a class is when you have static class that access Session values by strong names so you get intellisense within the project.

    Monday, April 8, 2019 12:06 PM
  • User746671234 posted
    But when error fires it goes to global.asax and there also I cannot get session
    Monday, April 8, 2019 12:10 PM
  • User753101303 posted

    Maybe the null reference is not on what you think? Add a breakpoint so that you can inspect variables and make 100% sure about which variable is null.

    Monday, April 8, 2019 12:11 PM
  • User746671234 posted

    I debug all.  I simply made a form and add session in variable on form load and then I run that form and change the url.  it goes to global.asax and here I didn't find the session value.  I added the session value in watch list and I found that when error comes it says 'session' is not declared.  It may be inaccessible due to its protection level.

    Monday, April 8, 2019 8:04 PM
  • User475983607 posted

    I debug all.  I simply made a form and add session in variable on form load and then I run that form and change the url.  it goes to global.asax and here I didn't find the session value.  I added the session value in watch list and I found that when error comes it says 'session' is not declared.  It may be inaccessible due to its protection level.

    There are several global.asax events where Session is not available.   Rather than us guessing how your code works, how about you post sample code that reproduces this issue.

    Monday, April 8, 2019 8:10 PM
  • User746671234 posted

    test.aspx

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
            Session("MyName") = "ravikant"
        End Sub

    global.asax

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    'MsgBox(System.Web.HttpContext.Current.Session("MyName"))
            
            Dim lastError As Exception = Server.GetLastError()
            If (lastError IsNot Nothing AndAlso lastError.Message <> "File does not exist.") AndAlso (lastError.Message <> "Thread was being aborted") AndAlso (lastError.Message <> "The client disconnected.") Then
                Dim xCl As New CommonClass
                xCl.SendMail(lastError, HisIp)
    End Sub

    commonclass

    Public Sub SendMail(ByVal i_oErr As Exception, ByVal ClientIp As String)
            Try
    --not getting session here
    MsgBox(System.Web.HttpContext.Current.Session("MyName"))
    Catch ex As Exception
    end try

    I'm not getting session value neither in global nor in class

    Monday, April 8, 2019 8:14 PM
  • User475983607 posted

    The steps to reproduce the error are not very clear.  Errors that happen before AcquireRequestState will not have Session as Session has not started yet.

    After seeing your code I recommend you rethink the approach and use more robust exception handling.  

    Secondly, never do this.

    Public Sub SendMail(ByVal i_oErr As Exception, ByVal ClientIp As String)
            Try
    --not getting session here
    MsgBox(System.Web.HttpContext.Current.Session("MyName"))
    Catch ex As Exception
    end try

    Always pass Session values to another class via parameters.

    Public Sub SendMail(ByVal i_oErr As Exception, ByVal ClientIp As String, ByVal MyName as String)

    Never implement an empty Catch block!

    Lastly, MsgBox pops up on the server and is not recommended for development.  

    Please read the docs for proper exception handling and exception logging.

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling

    Monday, April 8, 2019 8:30 PM
  • User746671234 posted

    1] I think session has started on form load.

    2] after I load the form I get an error so it goes to global.asax then why I am not getting session variable here.

    3] I am using msgbox on locally just to test the value

    Monday, April 8, 2019 8:39 PM
  • User475983607 posted

    ravininave

    1] I think session has started on form load.

    2] after I load the form I get an error so it goes to global.asax then why I am not getting session variable here.

    3] I am using msgbox on locally just to test the value

    Again, we need code that actually runs and compiles to reproduce this issue.  There is no indication how or when the exception is fired. Perhaps you are firing the exception right after setting Session and that is why Session is not working as expected.

    I made a very simple test and cannot reproduce this issue.  Session is clearly displayed in the Visual Studio Console.

    Public Class CommonClass
        Public Sub SendMail(ByVal i_oErr As Exception, ByVal ClientIp As String, ByVal MyName As String)
            System.Diagnostics.Debug.WriteLine("Error Message: " & i_oErr.Message)
            System.Diagnostics.Debug.WriteLine("ClientIp: " & ClientIp)
            System.Diagnostics.Debug.WriteLine("MyName: " & MyName)
        End Sub
    End Class
        Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    
            Dim lastError As Exception = Server.GetLastError()
            If (lastError IsNot Nothing AndAlso lastError.Message <> "File does not exist.") AndAlso (lastError.Message <> "Thread was being aborted") AndAlso (lastError.Message <> "The client disconnected.") Then
                Dim xCl As New CommonClass
                xCl.SendMail(lastError, "127.0.0.1", System.Web.HttpContext.Current.Session("MyName"))
            End If
    
        End Sub
    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ExceptionSessionTest.aspx.vb" Inherits="VbWebApplication.ExceptionSessionTest" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            </div>
        </form>
    </body>
    </html>
    
    Public Class ExceptionSessionTest
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                Session("MyName") = "ravikant"
            End If
        End Sub
    
        Protected Sub Button1_Click(sender As Object, e As EventArgs)
            Throw New Exception("This is a test!")
        End Sub
    End Class

    Results

    Exception thrown: 'System.Exception' in VbWebApplication.dll
    An exception of type 'System.Exception' occurred in VbWebApplication.dll but was not handled in user code
    This is a test!
    
    Error Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
    ClientIp: 127.0.0.1
    MyName: ravikant
    The thread 0x24fc has exited with code 0 (0x0).
    The thread 0x6dd8 has exited with code 0 (0x0).

    However, I still feel that you exception handling is very fragile and need to rethinking the design.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 8, 2019 8:59 PM
  • User746671234 posted

    Well thank you mgebhard.  I appreciate your patience with me.  I will try to write the error handler as you described.  I think I will get the user name by this way.  Will try on live server and let you know.  It seems that issue has been solved and also I learnt a new way.

    Thank you mate.

    Monday, April 8, 2019 9:06 PM