"The day you stop learning SharePoint is the day you stop using it."

Using SPSecurity.RunWithElevatedPrivileges with SPContext class

Using SPSecurity.RunWithElevatedPrivileges with SPContext class.

If you have implemented your code similar to the Code Snippet 1 then you might run into exception. Many developers implement their code, similar to the Code Snippet 1 and runs into exception such as Access Denied, “sign in as a different user”. This is because… the below code is not the correct way of using SPSecurity.RunWithElevatedPrivileges

When you declare SPSite elevatedSite = SPContext.Current.Site; or SPWeb elevatedWeb = SPContext.Current.Web;

these statements runs with the current login user permission and not the System Account. Therefore you might face an Access Denied exception when updating a list or any content since the code is running under current login user credentials who might have no add/contribute access on the list. No matter if you have declared
SPContext under SPSecurity.RunWithElevatedPrivileges, still the code will execute with the current login user permission.

Code Snippet 1 (Incorrect way):

SPSecurity.RunWithElevatedPrivileges(delegate()
{
      SPSite spSite = SPContext.Current.Site;

      using (SPWeb spWeb = spSite.OpenWeb())
      {
         // Performing administrative actions here will give Access Denied exception.
      }
});


Code Snippet 2 (Correct Way):

Guid spSiteGUID = SPContext.Current.Site.ID;
Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
    {
       using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
       {
         //your code…
       }
   
    }
});

The above Code Snippet 2 automatically disposes the SPContext object and the SPSite and SPWeb objects are also automatically disposed once they leave the code block. No need to dispose SPSite and SPWeb objects explicitly when they are declared in using statement.

So the bottom line is SPContext does not works under SPSecurity.RunWithElevatedPrivileges.
Share:

0 comments:

SharePoint-StackExchange Moderator

Author's Profile

My photo
India
A SharePoint Enthusiast working as a Lead Solution Architect for an IT Software & Consulting Company in Mumbai. I believe in giving back to the community through which I also learn and develop and eventually grow as an individual and professional. This blog is a small contribution to the community where I live in and may help someone who is seeking knowledge like me.

Popular Posts

Powered by Blogger.

Contact Form

Name

Email *

Message *

Total Pageviews