static void

PreInit HttpModule

To change the master page - or theme. See also AuthorizetModule.

Web.config (IIS6/7)

Web.config- IIS6 in system.web

<httpModules>
    <add name="PreInitModule" type="PreInitModule"/>
</httpModules>

IIS7 in system.webServer:

<validation validateIntegratedModeConfiguration="false"/>
<modules>
    <add name="PreInitModule" type="PreInitModule"/>
</modules>

PreInitModule

using System;
using System.Web;
using System.Web.UI;
 
/// <summary>
/// HttpModule to change the master page (and theme)
/// </summary>
public class PreInitModule : IHttpModule
{
    #region IHttpModule Members
 
    ///<summary>
    ///Initializes a module and prepares it to handle requests.
    ///</summary>
    ///<param name="context">An <see cref="T:System.Web.HttpApplication"></see> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += context_PreRequestHandlerExecute;
    }
 
    ///<summary>
    ///Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"></see>.
    ///</summary>
    public void Dispose()
    {
    }
 
    #endregion
 
    private static void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null) page.PreInit += page_PreInit;
    }
 
 
    static void page_PreInit(object sender, EventArgs e)
    {
        Page page = sender as Page;
        if (page != null)
            page.MasterPageFile = "~/site2.master"; //replace with Session[] or Cookie...
    }
}

Variation for authorization

You can use AuthorizeRequest if you don't use Session. If you use Session and it's not an asp page, see the AuthorizeModule.

public void Init(HttpApplication context)
{
    context.PreRequestHandlerExecute += MyAuthorizeRequest;
    //if not using session do this=//context.AuthorizeRequest += MyAuthorizeRequest;
}
 
static void MyAuthorizeRequest(object sender, EventArgs e)
{
    //if they are not authorized, redirect to login
    if (!SessionManager.IsAuthorized())
    {
        HttpContext context = ((HttpApplication)sender).Context;
        context.Response.Redirect("~/login.aspx");
    }
}