5

Below code throw an exception at "Item.Update();"

    private void AddEmail()
    {
        site = SPContext.Current.Site;
        web = site.RootWeb;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (site = SPContext.Current.Site)
            {
                using (web = site.RootWeb)
                {
                    try
                    {
                        SPList list = web.Lists["Newsletter"];
                        SPListItem Item = list.Items.Add();
                        web.AllowUnsafeUpdates = true;
                        Item["Title"] = txtEmail.Text;
                        Item.Update();
                        SendEmail();

                        txtEmail.Text = "";
                    }
                    catch (Exception ex)
                    {
                        ltrMessage.Text = ex.Message;
                    }
                }
            }
        });
    }

Can anyone help me get over this ?

1 Answer 1

9

When running inside RunWithElevatedPrivileges, do not use SPContext.Current. Instead create a new SPSite object, passing in SPContext.Current.Site.Url.

2
  • 1
    Also 'using' would release dispose SPContext,Current.Site ! Feb 23, 2017 at 11:26
  • 99% of the time, RunwithElevatedPrivileges is unnecessary, just instantiate SPSite with SPUserToken.SystemAccount as the second parameter.
    – James Love
    Feb 23, 2017 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.