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.
So the bottom line is
0 comments:
Post a Comment