Quantcast
Channel: Emad Gabriel – Emad's Blog
Viewing all articles
Browse latest Browse all 29

Access Denied for code running inside RunWithElevatedPrivileges

$
0
0

I had a custom web part that is running code that required elevated privileges and was running within SPSecurity.runWithElevatedPrivileges  as below

 

SPSecurity.RunWithElevatedPrivileges(delegate()

{

   SPSite siteColl = SPContext.Current.Site;

   ….

}

I kept throwing an access denied error.

after some investigation I found the solution at this useful blog.

http://blogs.msdn.com/b/sasohail/archive/2010/10/31/access-denied-within-spsecurity-runwithelevatedprivileges.aspx

 

the problem in short is, I was using a reference to the SPSite obtained from the SPContext. This reference to SPSite was created before the code entered the RunWithElevatedPrivileges block. Therefore, the reference to the SPSite was running under the current user privileges even though it was placed within the RunWithElevatedPrivileges block.

 

The solution is to obtain a new reference to the SPSite created within the RunWithElevatedPrivileges block as shown below.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite siteColl = new SPSite(SPContext.Current.Site.ID))
    ….

}



Viewing all articles
Browse latest Browse all 29

Trending Articles