page_load event in Master and Content Pages

Kent picture Kent · May 9, 2011 · Viewed 7.5k times · Source

Here is the sequence in which events occur when a master page is merged with a content page:

http://msdn.microsoft.com/en-us/library/dct97kc3.aspx

So, my problem is:

I have one login page (not use master page), one master page, and hundreds of content page.

I check login session Session["loggedInUser"] in master page (if not logged in, redirect to login page)

So, when I don't log in, if I type the address of one content page, it must check login session in master page and redirect to login page, right? But it has two cases here:

If in content page, I don't use anything related to Session["loggedInUser"], it will redirect to login page, so, it's OK here!

The second case: if I use Session["loggedInUser"] to display Username in content page for example:

UserInfo loggedInUser = (UserInfo)Session["loggedInUser"];

it will return null object here, because the page_load in content page is fired before page_load in master page, so it thows null object instead of redirecting to login page.

I also tried Page_PreInit in master page but no help

protected void Page_PreInit(object sender, EventArgs e)
{
    if (Session["loggedInUser"] == null)
    {
        Response.Redirect("~/Login.aspx");
    }
}

Any suggestion?

Answer

Jackson Pope picture Jackson Pope · May 9, 2011

You could check for Session["loggedInUser"] in the content Page's Page_PreRender() rather than Page_Load()or alternatively, do the master page check in the Page_Init() rather than Page_Load(). We had the same problem and went with the Master page Page_Init() option, so that we could still use Page_Load() in all the Content pages.

Edit: It's Page_Init() not PreInit().