Sharepoint MasterPage via HttpModule

If you would like to set the Sharepoint Master Page via HttpModule where no Publishing feature is activated and if you dont want to touch the system master pages.

 

using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ApplicationHttpModule
{
   public class ApplicationMasterModule:IHttpModule
   {
         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)
                 {
                 if (page.MasterPageFile != null)
                     {
                     if (page.MasterPageFile.Contains("application.master"))
                         {
                         page.MasterPageFile = "/_layouts/MasterPages/Custom.master";
                         }
                     }
                 }
         }
        public void Dispose()
        {
        }
}

}

 

In sharepoint 2010 you dont have to add it under httpmodule in web.config rather you can add it under Modules Section in web.config . Under

<modules runAllManagedModulesForAllRequests="true">

you can add

<add name="MasterPageHttpModule" type="MasterPageHttpModule.CustomMasterPageModule,MasterPageHttpModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=————-" />

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami