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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0