I wanted to create a template web site with the ability to completely change its layout via the web.config file, and it was also a good excuse to look into HttpModules.
HttpModules are services that execute when the requests reach the webserver, you can use them to do whatever you want... like compressing the output before sending it to the client, parsing scripts and put them all in a single file, etc, etc, etc
This time, what I want to do is set the the page's MasterPage according to a value in the web.config file.
What I do is register for the page's PreInit method, and set the MasterPageFile property in the handler, like this:
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
page.PreInit += new EventHandler(page_PreInit);
}
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
page.MasterPageFile = "~/MasterPages/" + ConfigurationManager.AppSettings["MasterPageTheme"] + "/site.master";
}
In that example, you have to have a MaterPageTheme setting with the name of the folder that contains site.master.
Then you just need to register the module, and you are good to go
<httpModules>
<add name="MasterPageModule" type="MasterPageModule"/>
</httpModules>
You can download the code below, just drop it in the App_Code folder
MasterPageModule.zip (620.00 bytes)