1

I wanna get all users in SharePoint group but my SharePoint page got error

"Sorry, this site hasn't been shared with you"

I used SPSecurity.RunWithElevatedPrivileges(delegate{}); in my code but this error still occur

this is my code:

    return groups.Cast<SPGroup>().Any(g => g.Name == group) &&
                (SPContext.Current.Web.Groups.GetByName(group)?.Users?.Cast<SPUser>().Any(u => u.ID == user.ID) ?? false);
  • Can you share the entire code? – Cecilia Apr 24 '17 at 15:50
1

You are most likely creating the SPSite or SPWeb object outside the delegate, which is why you get access denied.

Below is probably what you are doing - obviously, not exactly like this, I hope not like this:

SPSite site = new SPSite("site_url_here");
SPWeb web = site.RootWeb;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // code using the web object from outside the delegate to get the members of a group.
});

From MSDN:

An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges. The same point applies to SPWeb objects and any other objects. You must create new objects inside the delegate if you need to execute the members of the objects with elevated privileges. If the new object must represent the same persisted entity as an object created outside the delegate, then you must reference identification information from the externally created object and use it to create the new object within the delegate. For example, if web is a reference to an SPWeb object created before the call to RunWithElevatedPrivileges, then the following code shows you would use the ID of its parent SPSite object to construct a new SPSite object.

If you already have the site/web objects used outside the delegate, then you can just refresh them inside the delegate like this:

SPWeb web = SPContext.Current.Web;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite elevatedSite = new SPSite(web.Site.ID))
    {
        using(SPWeb elevatedWeb = elevatedSite.OpenWeb(web.Url))
        {
            // get all group members here
        }
    }
});
| improve this answer | |

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.