Session not avaible in controller constructor

Last post 04-24-2008 4:18 AM by srulyt. 1 replies.

Sort Posts:

  • Session not avaible in controller constructor

    04-24-2008, 3:43 AM
    • Loading...
    • hudo
    • Joined on 05-08-2007, 9:11 PM
    • Croatia
    • Posts 39

    When I try access session variables in controller constructor ( public HomeController() ) i get exception, saying that object reference not set to instance of an object.

    Code:

     

    1        public class HomeController : Controller
    2        {
    3            private string samvar;
    4    
    5            public HomeController()
    6            {
    7                if (HttpContext.Session["test"] != null)                           // error line !
    8                {
    9                    samvar = (string)HttpContext.Session["test"];
    10               }
    11               else
    12               {
    13                   samvar = "test";
    14                   HttpContext.Session["test"] = samvar;
    15               }
    16           }
    17           public void Index()
    18           {
    19               RenderView("Index", samvar);
    20           }
     
    Session vars accessed from action method works fine.
    #define QUESTION ((bb) || !(bb))

    Hear me tweetting
    Filed under: ,
  • Re: Session not avaible in controller constructor

    04-24-2008, 4:18 AM
    • Loading...
    • srulyt
    • Joined on 02-02-2008, 1:16 PM
    • Posts 209

     The session context is not yet initialized when the controller constructor is called. Use application variables if you need to store some info before your action method is called

Page 1 of 1 (2 items)
Microsoft Communities
Page view counter