سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top