How to use Session in ASP.Net App_Code

It would be quite useful if we can use “Session” inside App_Code in ASP.Net. E.G. You may not need to pass the “Session” variable into the Method, You only need to call the Session(“Variable Name”) inside the method.

However when I try to type the following Code in the vb/cs page which is under App_Code folder. It shows the error like this.

VB.Net
Dim Var as String = Session(“VariableName”)

C#
string var = (string) Session[“VariableName”];

Error: The type or namespace name ‘HttpSessionState’ could not be found

Here it is the solutions:
To use Session variable inside App_Code Folder.

You need to import a references: Please see the sample code below.

VB.Net
Import System.Web.SessionState
C#
using System.Web.SessionState;

VB.Net

 Dim ses As  HttpSessionState = HttpContext.Current.Session
 Dim VarSession As String = “”
 If ses(“VariableName”) IsNot Nothing Then
     VarSession = DirectCast(ses(“VariableName”), String)
 End If

C#

HttpSessionState ses = HttpContext.Current.Session;
        string VarSession = “”;
        if (ses[“VariableName”] != null)
        {
            VarSession = (string)ses[“VariableName”];
        }

Hope you find it useful.

Happy Coding =).

Leave a Reply