views:

185

answers:

2

Using ASP.NET MVC when trying to get the information stored on my Session["objectName"] from the constructor, I see that the Session has not been set yet, but once the controller has been constructed then the Session contains the right information.

public class ABCController : Controller
{
   public ABCController() { var tmp = Session["Whatever"]; } //This line is null
   //But I know it has information

   public ActionResult Index() { var tmp = Session["Whatever"]; } //This works fine
}

Thanks

+1  A: 

The session is found in the HttpContext. HttpContext is provided to the controller as part of the ControllerContext. Since a ControllerContext isn't passed as an argument to the constructor, it isn't available until after the class has been created and the ControllerContext has been assigned. It should be available, however, in any method on the controller. I'm not sure how you could expect the properties of a class to be populated before the class constructor is called (unless they're static class properties, but that's not the case here).

tvanfosson
+1  A: 

Overwrite the Initialize method of Controller base class. The request context is passed to this method. The session context is part of the request context.

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
        var tmp = requestContext.HttpContext.Session["Whatever"];
    }

This method is called after creating the controller and before calling the action method.

Christian13467