Accessing context session variables in c#

GowthamanSS picture GowthamanSS · Mar 21, 2013 · Viewed 7.8k times · Source

I have an ASP.NET application and dll which extends IHttpModule. I have used the below method to save the session variables in httpcontext through

public class Handler : IHttpModule,IRequiresSessionState
  {

 public void Init(HttpApplication httpApp)
 {
    httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}

 public void PreRequestHandlerExecute(object sender, EventArgs e)
        {
                var context = ((HttpApplication)sender).Context;
                context.Session["myvariable"] = "Gowtham";
        }
}

and in my asp.net Default.aspx page I have used code to retrive value as

   public partial class _Default : System.Web.UI.Page, IRequiresSessionState
    {
    protected void Page_Load(object sender, EventArgs e)
        {
      String token = Context.Session["myvariable"].ToString();
    }
}

I am getting error response as

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.

In order to ensure whether the variables store in session I have crossed check by following method in class handler after storing the value in session as

  string ss = context.Session["myvariable"].ToString();

it well executed and retrieved the value from session.

Answer

Ruly picture Ruly · Mar 21, 2013

Why do you need to use Context and not Session directly? From the code I can only assume that you are going to set a value in the Session, and then read the value on page load. Rather than you do something like that, you can do this:

  1. Add a Global Application Class, Right click on your project, Add > New Item, choose Global Application Class, and on that file, insert the following code to initialize the value

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["myvariable"] = "Gowtham";
    }
    
  2. On the Page_Load, you can access by:

    if ( Session["myvariable"] != null ) {
        String token = Context.Session["myvariable"].ToString();
    }
    

Hope this help..