views:

106

answers:

2

hi,

i am trying to access Session variables in the constructor of a controller and ControllerContext it seems is always null.

When is the earliest the session variables are available?

thanks!

Edit: Example:

in one controller:

public HomeController()
    {
        MyClass test =   (MyClass)ControllerContext.HttpContext.Session["SessionClass"];
    //ControllerContext always null           
    }

when debugging, controllercontext is ALWAYS null. In the controller whose actionresult redirects to this controller, i have:

Session["SessionClass"] = class;

MyClass test = (MyClass )ControllerContext.HttpContext.Session["SessionClass"]; 
// this works fine! i can get varibale from session

return RedirectToAction("Index", "Home");

So, at what point is ControllerContext actually set? When can I access session variables?

A: 

Hello Joe Rob

Session variables are already available in the constructor call of your controller.

But those Sesison[] variables aren't freely available anywhere in your controller class.


-> You need to call them either in the constructor or in a method of your controller.

Furthermore those variables should have been set somewhere or their vaues will stay null.

According to your example you'll need to set your Session["SessionClass"] key somewhere before calling it in the constructor:

public ActionResult Details()
{
  Session["SessionClass"] = new MyClass() { // Set your class properties };

  return View((MyClass)Session["SessionClass"]);
}

Now we'll unbox that saved value from the session:

public HomeController()
{
  MyClass test = (MyClass)Session["SessionClass"];

  // Do stuff with `test` now
}

This should work fine within your controller.

Cheers

Shaharyar
hi, i've added code to show how i can't access them in the controller constructor. thanks for your help
joe rob
have you tried accessing them only with Session["KEY"].. this has to work.. I just tried it myself.
Shaharyar
perhaps because the controller in which controllercontext is null is inheriting from a base controller i created?
joe rob
A: 

Override Initialize():

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    requestContext.HttpContext.Session["blabla"] = "hello"; // do your stuff
}
Mauricio Scheffer
Great, this worked.Can you please explain why, or post a link to somewhere explaining why?thanks again!
joe rob
Just found out this question is actually a duplicate of http://stackoverflow.com/questions/1424548/why-my-session-variables-are-not-available-at-construction-of-a-controller
Mauricio Scheffer