Sharepoint RunWithElevatedPrivileges and Access Denied error
28/04/2010 3 Comments
Hi everyone,
in this short article i try to explain most common error of Access Denied cause by misusage of SPSecurity.RunWithElevatedPrivileges() method.
Here is the wrong code sample:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//never use like this
SPList list = SPContext.Current.Web.Lists["SomeList"];
SPListItem item = list.GetItemById(12);
item["Title"] = "Some Changes";
item.Update();
});
The code defined above cause Access Denied when a user request without privs. Beacuse SPContext still contains unpriviledged user rights.If you call any object from SPContext it work with actual user (unpriviledged) rights not the admin rights.
Now is the correct one:
Guid webID = SPContext.Current.Web.ID;
Guid siteID = SPContext.Current.Site.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["SomeList"]; //attention here !!!
SPListItem item = list.GetItemById(12);
item["Title"] = "Some Changes";
item.Update();
}
}
});
Yep its a little extra codding . I give you a good pattern for using this with more easy and shorter usage:
I created once a static class and add to my project this class named RunAsAdmin and one static method named Run which is taking a delegate method for run our RunWithElevatedPrivileges codes.
public static class RunAsAdmin
{
public delegate void RunWithAdminDelegate(SPSite site, SPWeb web);
public static void Run(RunWithAdminDelegate myDelegate)
{
Guid webID = SPContext.Current.Web.ID;
Guid siteID = SPContext.Current.Site.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
myDelegate.Invoke(site ,web );
}
}
});
}
}
Usage of this code is:
RunAsAdmin.Run((site,web)=>
{
SPList list = web.Lists["SomeList"];
SPListItem item = list.GetItemById(12);
item["Title"] = "Some Changes";
item.Update();
});
Its very useful)
Happy coding with sharepoint (if it is possible![]()

Thank you very much. Works straight. The RunAsAdmin is a Good Idea.
nice tip, but in my case i am using spmetal gen class and domain users who has read permission to the site get access denied. but other people who have higher rights are able to use the whole custom web part.
I am not updating in the list, i am reading a list and just add it the gridview no updates to the list
Any tips on that.
Thx, you save my day :p