Wednesday, September 23, 2009

Getting context using RunWithElevatedPrivileges

Title: Getting context using RunWithElevatedPrivileges


Scenario: Have you ever tried creating the SPSite and SPWeb context inside the RunWithElevatedPrivileges context? If you have done so, then you must have noticed that the context user is still the logged in user and is not elevated to the app_pool identity.
To get the right context, use the code as shown below.


Code:

SPSite siteColl = SPContext.Current.Site;
SPWeb webSite = siteColl.OpenWeb();

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteColl.ID))
{
using (SPWeb web = site.OpenWeb(site.ID))
{
// DO SOME THING IMP HERE
}
}
});

No comments: