Apply master page programmatically using PnP in SharePoint

In this SharePoint Tutorial, we will learn how to apply or change the master page programmatically in SharePoint Online using PnP Core CSOM Library.

If you are new to SharePoint PnP, following this article to know about PnP SharePoint Online Development using Patterns and Practices.

The given below references are used in the code:

  • Microsoft.SharePoint.Client;
  • OfficeDevPnP.Core;

Following functions are used in our code:

  • GetSharePointOnlineAuthenticatedContextTenant() used for Connecting to the SharePoint online site.
  • ServerRelativeUrl() used to get or sets the server relative URL of the web site.

If you have seen below snapshot, it is an Oslo master page of the site in SharePoint Online.

apply a master page to a site in sharepoint
apply a master page to a site in sharepoint

Suppose we need to change the master page from Oslo to Seattle in SharePoint site. Manually we can do this through the browser. But we can also do this programmatically using PnP Core CSOM in few lines of code.

Apply master page programmatically using PnP in SharePoint

Here I have created an asp.net application and I have added a button. Just click on the button, Apply the Master page of a site in SharePoint Online using the PnP core CSOM library.

This is a straight forward code for updating the master page of a site in SharePoint Online using PnP Core CSOM Library.


string siteURL = "https://domainName.sharepoint.com/sites/TSInfoPNP";
string userName = "******@doaminName.onmicrosoft.com";
string password = "******";
protected void btnApplyMasterPage_Click(object sender, EventArgs e)
		{
			applyMasterPage();
		}

void applyMasterPage()
{
	try
	{
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, userName, password))
     {
	Web web = ctx.Web;
	ctx.Load(web);
	ctx.ExecuteQueryRetry();
	web.MasterUrl = web.ServerRelativeUrl + "/_catalogs/masterpage/seattle.master";
	web.CustomMasterUrl = web.ServerRelativeUrl + "/_catalogs/masterpage/seattle.master";
	web.Update();
	ctx.ExecuteQueryRetry();
	lblApplyMasterPage.Text = "Applyed MastePage Successfully ";				 
     }
}
catch (Exception ex)
  {

lblApplyMasterPage.Text = "Problem in Applying MastePage in SharePoint Online";
   }
}

Run our Application and click on button “Apply MasterPage”.

apply master page sharepoint online using pnp
apply master page sharepoint online using pnp

See the difference of oslo and seattle master page. The Below snapshot our Master page oslo is changed to Seattle.

apply master page sharepoint online
apply master page sharepoint online

Following some below tutorial links of master page creation:

In this article, we learned about how to change or apply the master page in the SharePoint site using PnP Core CSOM Library.

>