简体   繁体   中英

why RunWithElevatedPrivileges does not work in itemAdded eventreceiver?

in my eventreceiver project, itemAdded function, my code is going to add item to a second list but it is not working for some user with low privilege

SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(properties.Web.ID))
                    {
                        web.AllowUnsafeUpdates = true;
                        //my code
                        web.AllowUnsafeUpdates = false;
                    }
                 }
             }

Please be sure to use the elevated web when getting the SPList object. Not use the SPWeb from the current SPContext or event receiver properties.

So in Your case getting the list should look like:



    SPSecurity.RunWithElevatedPrivileges(delegate ()
    {
        using (SPSite site = new SPSite(properties.SiteId))
        {
            using (SPWeb web = site.OpenWeb(properties.Web.ID))
            {
                web.AllowUnsafeUpdates = true;
                SPList someList = web.Lists.tryGetList("LISTNAME");
                SPListItem newItem = someList.AddItem();
                // .... update columns and newItem.Update()
                web.AllowUnsafeUpdates = false;
            }
        }
    }

if this doesn't do the trick please provide a bit more code to check and maybe the error that is present.

I wrote some code (LogInfo("event@receiver@ starting!");) to logged what is going on in my code, surprisingly I found out even first line of ItemAdded Function did not execute!!! Because nothing found in shapreoint logs.It means It did not enter ItemAdded function or something else. here is my code:

public override void ItemAdded(SPItemEventProperties properties)
{
    LoLogInfo("event@receiver@ starting!");
    SPSecurity.RunWithElevatedPrivileges(delegate ()
    {
        LogInfo("event@receiver@ first step!");
        using (SPSite site = new SPSite(properties.SiteId))
        {
            LogInfo("event@receiver@ second step!");
            using (SPWeb web = site.OpenWeb(properties.Web.ID))
            {
                LogInfo("event@receiver@ third step!");
                SPList activeList = web.Lists.TryGetList(properties.List.Title);
                SPList finalList = web.Lists[FinalListName];
                web.AllowUnsafeUpdates = true;
                SPListItem finalListItem = finalList.AddItem();
                LogInfo("event@receiver@ forth step!");
                //some other code here
                web.AllowUnsafeUpdates = false;
                }
         }                
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM