Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I want to get a list item that the current user does not have access to but I need to get it in code. When I use SPSecurity.RunWithElevatedPrivileges that does not work.

It's because I'm using the Web object of current context in application page.

If I want to make the code work I have to build another SPSite and SPWeb object in RunWithElevatedPrivileges delegate but I don't want to do that.

How can I achieve this using the Current Web Context in Application Page?

share|improve this question

3 Answers 3

up vote 12 down vote accepted

You have to instantiate new SPSite and SPWeb objects inside your RunWithElevatedPrivileges() delegate using the ID properties of the current context's SPSite and SPWeb objects:

Guid siteId = SPContext.Current.Site.ID;
Guid webId = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteId))
    {
        using (SPWeb web = site.OpenWeb(webId))
        {
            // Your code here
        }
    }
});

May I ask why you "don't want to" create new SPSite and SPWeb objects in your RunWithElevatedPrivileges() delegate? If you use the design pattern I've demonstrated above, you don't have to worry about calling Dispose() on the new objects you've created.

share|improve this answer
    
thank you danny I'm Convinced. –  Pouyan Aug 14 '11 at 17:45
    
Can you tell me why we can't use: SPSite site = new SPCONTEXT.CURRENT.SITE? –  variable Aug 16 at 9:35

Thanks, it helped us a lot..saved a lot of time. Great answer :)

From SPSecurity.RunWithElevatedPrivileges:

"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."

Basically, you must create new objects inside the delegate in order to execute with full control rights.

share|improve this answer

You should create new SPSite inside the SPSecurity.RunWithElevatedPrivileges block using either url or guid.

For in-depth information on SPSecurity.RunWithElevatedPrivileges and other impersonation techniques, Check this out :

Impersonation in SharePoint : An Extreme Overview

share|improve this answer
    
Your post is very helpful. Thank you! –  Roman Jul 15 '12 at 0:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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