0

The following code, though run with elevated privildges, redirects to an access denied error page saying "You are currently signed in as: (my non-admin account)." What am I doing wrong?

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {

        SPGroup group = SPContext.Current.Web.Groups["Group Name"];

        foreach (SPUser user in group.Users)
        {
           string email = CustomMethodGetsEmailFromProfile(user);
           SPUtility.SendEmail(...);
        }

     });

If I comment out the foreach loop, it works fine but defeats the purpose. Recall, I'm getting access denied. There's a few null checks that I didn't include as I'm writing this from memory. Thanks in advance for any help.

2

You can't/shouldn't use SPContext when elevating privileges, as the objects represented within it were created under a different (...in this case probably one with less privileges) security context. Try something like this:

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                {
                     // then your code
                }
            }
        });

Should do the trick.

  • Rick, could you please mark it as answered so it's clear to others folks that this is an answered question. – Rob D'Oria Jul 29 '11 at 20:25

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.