BrunoLM
BrunoLM

Reputation: 100351

How to make a code run on all aspx pages?

I need to create a code that reads the QueryString and set a value on the Session and on the end of the page I need to clear the Session.

How can I make a code like this to run on all .aspx pages?

Upvotes: 2

Views: 313

Answers (7)

Vivian River
Vivian River

Reputation: 32400

I used the method of writing a class to inherit from System.Web.UI.Page. However, I did not find the implementation of this method to be obvious. Here is the code that I eventually wrote:

public class BasePage : System.Web.UI.Page
{                        
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        // Code here will be run when any page loads that inherits from BasePage
        }                                                
    }
}

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77556

Or just use Global.asax: http://en.wikipedia.org/wiki/Global.asax

Upvotes: 4

Cylon Cat
Cylon Cat

Reputation: 7201

An easy way to include code that is part of all pages is to subclass Windows.Web.UI.Page, and have all your pages inherit from this new class, instead of Windows.Web.UI.Page. The new class can register for page events, independently from each individual page.

Another option, if you don't want it to be part of each page, and you want to ensure that it runs even if a developer doesn't inherit your new page subclass, is to write an HTTPModule. This hooks into the ASP.NET processing pipeline, and you can trigger off pipeline events, such as authentication or displaying pages. You can write an HTTPHandler and run it out of the pipeline as well. (All pages implement IHTTPHandler, somewhere up the chain.)

Upvotes: 0

Peter
Peter

Reputation: 38495

well as i see it you got 2 solutions

  1. Use a master page and do it there

  2. Inherit Page and use that as base class on all your pages

One question why must it be stored in a session? this will give your problems if the same user executes 2 pages at the same time (the first to finish will clear the sesson for the other page)

if you only need the data while the page runs you can just save it in a normal variable, else use the viewState!

Upvotes: 4

user333306
user333306

Reputation:

Create a class that inherit from Page that you will use instead of Page.

Alternatively, you can use a MasterPage if your application design allows that.

Upvotes: 2

citronas
citronas

Reputation: 19365

Two possibilities are:

  • Create a class that inherits from System.Web.UI.Page. Insert your code there and all your pages inherit from that class instead of System.Web.UI.Page.
  • Create a HttpModule

Upvotes: 8

fARcRY
fARcRY

Reputation: 2358

By putting the code in a basepage and letting all your .aspx pages inherit from the basepage.

Upvotes: 1

Related Questions