views:

160

answers:

4

Is there a way you can call a function, or make a file that runs before every page load. I want to be able to check if they have a valid session before showing the page.

+3  A: 

You should look at implementing one of the event handlers that can be called when a page is rendered.

For more information see the page life cycle page on MSDN.

If you simply want to not display anything then the PreInit() event might be the one you want.

If you want to display different content then the PreLoad() event might be more appropriate.

ChrisF
+2  A: 

As Chris has said you need to respond to one of the events that occur during page life cycle. If you want to make check in just one place you can derive a class from Page class and make all your pages implement that class.

Giorgi
+2  A: 

Just check if session is null on Page_Preinit event of the page:

        private void Page_PreInit(object sender, System.EventArgs e) {
          if ((Session == null)) {
            // Do something here
          }
        }

If you need to do this on a lot of pages, simply create a base page, put the code there, make you pages inherit that basepage.

You should really familiarize your self with the page lifecycle as ChrisF suggested.

-D

Diego C.
That's not C#, you know.
Steven Sudit
Oops! my bad, thanks Steven for pointing that out, I corrected the language
Diego C.
+1 for mentioning the use of a base page class.
Steven Sudit
A: 

If you are talking about running common code across multiple different pages before page load, it sounds like you are looking for MasterPages, where you implement your session check in the Master Page.

Serapth