Skip to main content

Cloud

Accessing SharePoint objects within Elevated Privileges

When trying to use a SharePoint object (ie SPWeb) within a elevated privileges, you can’t just re-use an existing object you created outside the block – it will fail. You need to create a new instance of the object within the elevated block.

In this example I’m assuming you are first getting the SPWeb object using the current Context, probably so that you can do some work with the object. At some point in the code, you need to elevate the privileges. You won’t be able to use your existing SPWeb object, because it was created with lower privileges.

I’ve had success by grabbing the SPSite.ID and SPWeb.ID Guids, and then using them within the block to create a new instance.

//declare Guids

private Guid spWebId;

private Guid spSiteId;

<…>

//get current site

SPWeb currentWeb = SPControl.GetContextWeb(Context);

//for future reference:

spWebId = currentWeb.ID;

spSiteId = currentWeb.Site.ID;

<…>

//run some code with elevated privileges

SPSecurity.CodeToRunElevated myCodeToRun = new SPSecurity.CodeToRunElevated(myCode);

SPSecurity.RunWithElevatedPrivileges(myCodeToRun);

//Here’s the code running elevated

private void myCode() {

//get currentWeb again, using the GUIDs

SPSite currentSite = new SPSite(spSiteId);

SPWeb currentWeb2 = currentSite.OpenWeb(spWebId);

<…>

}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.