All About SharePoint

Liedong(Ken) Zheng,SharePoint Leader at SIMPLOT

Using SPSecurity.RunWithElevatedPrivileges with SPContext.Current

Posted by ken zheng on November 23, 2010

You may get exception if you using RunWithElevatedPrivileges like below

    SPSecurity.RunWithElevatedPrivileges(delegate() {

        SPSite siteColl =    SPContext.Current.Site;
        SPWeb site = SPContext.Current.Web;
     //Code to execute

    });

That’s because SPSite object permissions are determined when they are created, so SPContext.Current.Site will already have the permissions of the current user even if you get the reference within RWEP.

The code should look like below:

SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
        //Code to execute
    }
  }
});
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: