page_load event in Master and Content Pages
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?
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:
if (Session["loggedInUser"] != null)
{ ... }
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:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
base.OnLoad(e);
}
}
And in the content page, instead of inheriting from Page
, I change to BasePage
and it works perfectly
Thanks for all of your support
Nice day ;)
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()
.
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
精彩评论