Friday, October 11, 2013

SharePoint Impersonation mistake

SharePoint API give us function  SPSecurity.RunWithElevatedPrivileges to impersonate by system account users. Some users make mistake in using it by using current site instead of initiate new SPSite.:

SPSecurity.RunWithElevatedPrivileges(() =>
{

using ( SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
....................
}
}
}
});

Developer need to use:
SPSite site = new SPSite(SPContext.Current.Site.Url)

instead of:
SPSite site = SPContext.Current.Site

Code will be:
SPSecurity.RunWithElevatedPrivileges(() =>
{

using ( SPSite site = new SPSite(SPContext.Current.Site.Url) )
{
using (SPWeb web = site.OpenWeb())
{
....................
}
}
}
});

No comments: