Reputation: 7611
On my Master Page, I have a little method in the Page_Load
event that checks to see if a user is logged in, and redirects them to the Login page if not.
The problem is that for some of my pages the Page_Load
events presume a users logged are in, and these events seems to fire before the login check in the master page, which causes errors.
What are some ways around this? Any events I can use other than Page_Load in my pages, that'll fire after the master page?
Upvotes: 24
Views: 18969
Reputation: 50728
You are going to have to check whether the user is logged in for those features, by doing: if (this.Page.User.Identity.IsAuthenticated == true) { .. }
. Nothing can be assumed, which is what you are experiencing. You could also move your login check to Page_Init, or even move it to an HTTP module that runs on every page load; there you have access to a wide array of events including application authentication/authorization.
If you are using forms authentication, you can use the configuration file to drive this instead, via the authorization element.
<system.web>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
</system.web>
<location path="login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
HTH.
Upvotes: 1
Reputation: 2074
If you need things to occur in the MasterPage Page_Load before the page events, use the Page_PreRender
protected void Page_PreRender(object sender, EventArgs e)
in the actual page.
Upvotes: 2
Reputation: 3761
You have a rich Page Cycle with lots of events to use.
Perhaps you could use Page_Init
to check if the user is logged-in in the Master Page.
Or use Page_PreRender
in the other pages.
Upvotes: 27