Tuesday, March 17, 2009

RunWithElevatedPrivileges is not working - invalid/wrong security context

To fix this you need to get a news ite reference

SPSecurity.RunWithElevatedPrivileges(delegate()

{

//Gets a new security context using SHAREPOINT\system
//or by using (SPSite oSite = new SPSite(this.Page.Request.Url.ToString()))

using(SPSite oSite = new SPSite(SPContext.Current.Site.ID))
{
   using (SPWeb oWeb = oSite.OpenWeb())
   {
    oWeb.AllowUnsafeUpdates = true;
    // Add a record to the new list
    SPList oList = oWeb.Lists["myListName"];
    if (oList != null)
   {
    SPListItem item = oList.Items.Add();
    item["Title"] = "new item";

    // item.update to committ
    item.Update();
    }
 }
}
});

0 comments:

Post a Comment