.NET Tips and Tricks

Blog archive

Manage Pages Across the Web Site from One Location

Sometimes there is some processing that needs to be added to every page on the site. For instance, I had a client who wanted to add code to every WebForm's PreInit event to set Page's Theme property dynamically. Changing every PreInit event in every page sounded like the definition of no fun at all.

But there's a better solution. One place to put code required on every page is in an HttpModule. HttpModules process every page request that comes into the site. You can create your own HttpModule so that, when a request for a page comes to the site, you can add to code to any event on the page.

The first step is to create a class that implements the IHttpModule interface:

Imports System
Imports System.Web
Imports System.Web.UI

Public Class ManageTheme
  Implements IHttpModule
In the class' Init method, tie a method of your own to the PreRequestHandlerExecute event that's fired by ASP.NET before processing a page. You'll use your method to customize the page's processing. You can get to the PreRequestHandlerExecute event through the HttpApplication object passed to the Init method:
 Public Sub Init(Context As HttpApplication)_
            Implements IHttpModule.Init
         AddHandler Context.PreRequestHandlerExecute, 
                     AddressOf WireUpPreInitEvent

  End Sub
Your method will now be called whenever a page is processed. In your method, you can add code to any of the page's events. This code ties a method called sitePreInit to the Page's PreInit event:
 Sub WireUpPreInitEvent(sender As Object, e As EventArgs)
   If TypeOf HttpContext.Current.CurrentHandler Is Page Then
     Dim p As Page
     p = CType(HttpContext.Current.CurrentHandler, Page)
     If p IsNot Nothing Then
       AddHandler p.PreInit, AddressOf SitePreInit
     End If
   End If
 End Sub
Finally, you can add the code you want to run on every page on your site to the event you've wired up:
  Sub SitePreInit(sender As Object, e As EventArgs)
    If TypeOf sender Is Page Then
      Dim p As Page
      p = CType(sender, Page)
      If p IsNot  Nothing Then
        p.Theme = "MyTheme"
      End If
    End If
  End Sub

Public Sub Dispose() _
  Implements System.Web.IHttpModule.Dispose

End Sub

The last step is to update the httpModules element to incorporate your module into your site's processing pipeline:

<httpModules>
  <add name="MyHttpModule" type="ManageTheme"/>
</httpModules>

Posted by Peter Vogel on 08/12/2011


comments powered by Disqus

Featured

Subscribe on YouTube