How to add a user to a SharePoint group programmatically - access is denied

I tried and tried to add the user to the SharePoint group using C # programmatically (using an administrator without a site). If I am registered as a site administrator, it works fine ... but if I am registered as an administrator other than the site, then I am denied access. After some investigation, I found that I need to either “personalize” the user (which doesn't seem to work) or “provide the user”, so I ended up in this code (which worked for some people). Can someone explain to me why the following is not working and still giving me an Access is Denied error?

SPSecurity.RunWithElevatedPrivileges(delegate()

{

    using (SPSite site = new SPSite(SPControl.GetContextSite(HttpContext.Current).Url)) //have also tried passing in the ID - doesn't make a difference

    {

        using (SPWeb web = site.OpenWeb())

        {

                web.AllowUnsafeUpdates = true;



                // add user to group

                SPGroup group = this.Web.Groups[groupList.Items[i].Value];

                SPUser spUser = web.EnsureUser(provider + ":" + user.UserName); //provider is previously defined

                spUser.Email = user.Email;

                spUser.Name = txtFullName.Text;

                group.AddUser(spUser);



                // update

                group.Update();

        }

    }

}
+3
source share
2

! this.Web.Groups web.Groups... .

+3

web.AllowUnsafeUpdates = true;, .

, , SPWeb AllowUnsafeUpdates, .

bool updates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;

// do your thing

web.AllowUnsafeUpdates = updates;

, SPWeb. catch try finally, web.AllowUnsafeUpdates = updates; finally.

, , , true, . SharePoint powershell , SPWeb .

0

Source: https://habr.com/ru/post/1750610/


All Articles