C# – Session variable and Masterpages

asp.netcmaster-pagessession

I want to log a users session on my site. I was hoping to just set a session variable. But the initialisation of it is giving me problems.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SESSION_GUID"] == null)
    {
        Session["SESSION_GUID"] = Guid.NewGuid().ToString();
        Response.Redirect(Request.Url.ToString(), true);
        return;
    }
    lnkUpload.Visible =  (Session["LOGGED_IN"] != null);
    btnLogout.Visible = (lnkUpload.Visible);
}

It seems that the masterpage is creating the variable OK, but the rest of the pages load (ones using that master page). So in my log, I am seeing TWO hits. One with no session ID set, and the second hit has a session id.

Any idea why the child page of this masterpage is loading twice? This only happens on the first request to the site. After that, the session is working fine and we only get one hit.

Best Answer

The Page_Load event of the content page will be called before the Page_Load of the master page as seen in steps 6-7 in the ASP.NET Page Lifecycle

The master page Page_Init event is called before the content page Page_Init event though, so if all you're doing is checking for Session, probably best to handle it in the Page_Init of the master page and redirect there. This could cause problems based on how other code in your project looks but conceptually, one of the first things you are wanting to do is check Session and handle properly so, you don't need page/controls to load before handling the redirect.

Related Topic