Search code examples
sharepointsharepoint-2010web-partselevated-privileges

Update Sharepoint List with elevated privileges


In a Webpart a user without any privileges needs to read and update a Sharepoint list.

Elevating privileges works ok for reading the list, but when I try to update the same list, throws a Exception. How is it possible to update a list with elevated privileges?

SPSecurity.RunWithElevatedPrivileges(delegate()
{ 

SPSite oSite = SPControl.GetContextSite(HttpContext.Current);
SPWeb oWeb = oSite.OpenWeb();
oWeb.AllowUnsafeUpdates = true;
SPListItemCollection listItems = oWeb.Lists["nameList"].Items;
SPListItem item = listItems.Add();

... 

item.Update(); // Throws Exception
});

Solution

  • The problem was the creation of the SPSite.

    The correct code:

    SPSite oSite = new SPSite(SPContext.Current.Site.ID); 
    SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID);                                 
    listItems  = oWeb.Lists["nameList"];