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?
I have 2 masterpages(1 for prelogin,2nd for afterlogin),home page is independent,logout page inherits postlogin page) in all postloginpage session chck if sessionnull(xyz)else(redirect loginpage) all this in Page_Init event of afterlogin.master................Successfull
Presumably, when you say you are using the
Session["loggedInUser"]
value, you are then calling.ToString()
method or similar to display it?In which case, you will need to check for a null object before using it. It would be best practice to check for the existance of the object before using any methods on it in any case, so:
Only if you are certain that the code will never be executed without the Session object being instantiated can you use methods without checking for a null reference.
http://msdn.microsoft.com/en-us/library/03sekbw5.aspx
Finally I've come up with a solution:
I create a class
BasePage
like this:And in the content page, instead of inheriting from
Page
, I change toBasePage
and it works perfectlyThanks for all of your support
Nice day ;)
You could check for
Session["loggedInUser"]
in the content Page'sPage_PreRender()
rather thanPage_Load()
or alternatively, do the master page check in thePage_Init()
rather thanPage_Load()
. We had the same problem and went with the Master pagePage_Init()
option, so that we could still usePage_Load()
in all the Content pages.Edit: It's
Page_Init()
notPreInit()
.