I have a custom webservice hosted in SharePoint. Within this service, I need to at times look up sites by id. Despite running code in an SPSecurity.RunWithElevatedPriviledges block, I still get Access exceptions for non-admin users when trying to look up a site by id.

From what I've read, I may be able to get around this problem by opening the site collection using a User token for an admin account. My problem is, how do I get a user token for an admin account?

Any help is greatly appreciated.


//Putting this inside RunWithElevatedPrivileges causes it to fail
var siteCollection = new SPSite(SITE_COLLECTION_URL);

SPSecurity.RunWithElevatedPrivileges(() =>
    //This throws for non-admins, regardless of being in a RunWithElevatedPriviledges block
    var web = siteCollection.AllWebs[webId]); 
  • RunWithElevatedPriviledges can be quirky. Can you please post the full block of code, including where the reference to the SPSite object is?
    – Dave Wise
    Jan 10, 2013 at 16:55
  • I've added additional detail.
    – MgSam
    Jan 10, 2013 at 17:00
  • RunWithElevatedPriveleges() should not be used to bypass SP security. It is intended to be used to make network calls as the application pool identity, not to circumvent security. User impersonation with a token is the correct way to do this. Jan 10, 2013 at 19:37

1 Answer 1


In order to properly use RunWithElevatedPrivileges(), you need to move the new SPSite() call inside the elevated block. otherwise it will get the SPSite reference using the ID of the user instead of the App Pool ID.

from Microsoft: "An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges."

  • Ah, ok. I remember why I wasn't doing this. I need the URL of the site collection not hard coded, which I was getting from SPContext.Current.Site.Url. This is null when you're inside of a RunWithElevatedPrivileges block. However, I realized I can just capture the URL outside of the block first. Thanks.
    – MgSam
    Jan 10, 2013 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.