Inheriting the Current Master Page for a Custom Application Page

To inherit the master page from the current site being browsed in a custom application page (i.e. a page that resides in the “_layouts” directory), you can use the following PreInit method:

private void Page_PreInit(object sender, EventArgs e)
        {
            System.Web.UI.Page page = sender as System.Web.UI.Page;
            if (page == null) return;
            if (page.MasterPageFile == null) return;

            HttpContext context = HttpContext.Current;
            string currUrl = context.Request.Url.ToString();
            string basepath = currUrl.Substring(0, currUrl.IndexOf(context.Request.Url.Host) + context.Request.Url.Host.Length);
            //Use RawUrl, otherwise it will always use the root web.
            currUrl = context.Request.RawUrl;
            if (currUrl.ToLower().Contains("/_layouts/") &&
                page.MasterPageFile.ToLower().EndsWith("application.master"))
            {
                currUrl = currUrl.Substring(0, currUrl.ToLower().IndexOf("/_layouts/"));
                using (SPSite site = new SPSite(basepath + currUrl))
                {
                    using (SPWeb web = site.OpenWeb(currUrl))
                    {
                        page.MasterPageFile = web.MasterUrl;
                    }
                }
            }
        }

Just add the code above to your code behind, and your custom page will now inherit the look and feel of the site it is currently in.

Bookmark and Share
Leave a comment

2 Comments.

  1. I have created a custom application page and would like to inherit the site’s master page that it will be used on. I tried to add this code in but it seemed to do nothing. I recieved no errors, but it also didn’t seem to call the master page. Is there something I need to change in the code?

  2. @AP – Are you working with a code behind or with inline script? You could try putting some Response.Write() calls in the PreInit method to validate that a valid page is found and/or a valid masterpage is attached to the application page you are attempting to modify.

Leave a Reply


[ Ctrl + Enter ]