Avoid using the Session in The Page Constructor

While I'm helping the Folks on asp.net forums, I noticed that there is a lot of develoeprs trying to access the Http Session in Page Constructor !

Most of them used this to Implement a kind of Secured Base Page  that checks the session value ,and if its missing , it will redirect to login or whatever page.

some of them write this Class :

public class AdminSecuredPage : System.Web.UI.Page
{

    public AdminSecuredPage()
    {
        if (Session["AdminUser"] == null) {
            Response.Redirect("~/login.aspx");
        }

    }

}

Note that the above class will throws HttpException ,

which tells :

"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration> ..."
 

 well the above exception will be thrown because the session is not ready when the Page constructor was called .

 

The Solution : 

One solution is to Move the Code from Page Constructor to  Page_init , Note that the page_init for this class will be called before the the Page_init of its Sub Page Class,

so you can check the Session value as follows:

public class AdminSecuredPage : System.Web.UI.Page
{
    public AdminSecuredPage()
    {}
  
    protected override void OnInit(EventArgs e)
    {
        // if the user is not Admin , redirect to Login Page
        if (Session["AdminUser"] == null)
            Response.Redirect("~/login.aspx");

        // this needed to initialize its base page class
        base.OnInit(e);
    }
}

 Hope This can help some one there ...
 and please ,if anyone has a better or other solutions , i will be happy to hear that ...

 

Best Regards,

Anas Ghanem