Tuesday 6 November 2012

Elevated Privileges

In SharePoint once in a while you need to run something in an anonymous environment that requires user credentials not very promising is it? well luckily you can run your request using elevated privileges, you just need to remember to grab your site and your web again inside your delegate.

 string welcomePageURL = null;

 if (PublishingWeb.IsPublishingWeb(SPContext.Current.Web))
 {
       SPSecurity.RunWithElevatedPrivileges(delegate()
       {
           using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
           {
               using (SPWeb elevatedWeb = elevatedSite.OpenWeb(SPContext.Current.Web.ID))
               {
                   PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(elevatedWeb);
                   welcomePageURL= pWeb.DefaultPage.ServerRelativeUrl;
               }
           }
       });
   }