开发者

How to make a code run on all aspx pages?

I need to create a code that reads the QueryString and set a 开发者_JAVA百科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?


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


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!


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


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.


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


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.)


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
        }                                                
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜