CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Home > CodeDigest >  
Technologies
 


How to Access Session variable, logged in users from an External Class File in ASP.Net ?
Submitted By Satheesh Babu B
On 2/28/2010 5:46:22 AM
Tags: asp.net,CodeDigest  

How to Access Session variable, logged in users from an External or Custom Class File in ASP.Net ?

 

By default, you will not be able to access the session variables in a external class file as you access in codebehind files. For example, like Session["key"]. This is because, the codebehind file inherits System.Web.UI.Page class which exposes all the properties like Session, Request, etc.

 

Moving forward, this little code snippet will help you to understand on how to access the session variables in an external class files.

 

The above said properties can be accessed via the current request's HttpContext object in any class files in you Asp.Net application. HttpContext class has a static property called Current which gives us the reference of current request's HttpContext object. The context object will give you the access to all the request specific objects like Request, Response, Server, Session, Cache, User objects.


Once we have the HttpContext object we can access those objects easily. The below code does that,

 

public class AccessContextInfo
{

       public AccessContextInfo()
       {

              //

              // TODO: Add constructor logic here

              //

       }

    public void AcessPageObjects()
    {

        HttpContext context = HttpContext.Current;

        context.Response.Write("Test");

        context.Session["Key"] = "Value";

//Get Logged in user

        string user = context.User.Identity.Name;     

    }

}


Note: Make sure you are including System.Web namespace in the class file.

Recent Codes
  • View All Codes..