Object reference not set to an instance of an object. RRS feed

  • Question

  •  public AccountController()

                SchoolModels SH = new SchoolModels();
                if (Session["IndependentSchool"] != null)
                    SH = (SchoolModels)Session["IndependentSchool"];



    Session["IndependentSchool"]  ==> error 

    how to solve

    Tuesday, September 18, 2018 7:21 AM

All replies

  • Your code translates to the following:

    1) Set SH to instance of SchoolModels.

    2) If Session contains something with key = "IndependentSchool", set SH to this value.

    In other words, when your code initially runs, no code ever place something into Session with that key yet.

    I suppose your code would do something to SH, then set it to Session at the end before returns.

    Tuesday, September 18, 2018 8:51 AM
  • This is really a web question. Please post questions related to web development in the ASP.NET forums.

    To save you from having to post this question there I can tell you the problem is that Session isn't available yet. You are trying to access this in your controller's constructor. At the point the constructor is created the HTTP context isn't set up yet. Session is part of the HTTP context and since it isn't available yet you get a null reference on the Session property. You can set a breakpoint on that line, hit the breakpoint and then mouse over it to see. 

    In general you shouldn't do anything in your controller constructor accept set up the fields based upon the parameters you're given. Everything else needs to wait until an actual request (action) is called. Refer to this article on the ASP.NET lifetime.

    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, September 18, 2018 2:26 PM