How to add a user to a SharePoint group programatically - Access is Denied
I have tried and tried to add a user to a SharePoint group using C# programatically (using a non-site admin). If I am logged in as a site admin, it works fine... but, if I am logged in as a non-site admin then I get an access is denied error. After doing some investigation I found that I needed to either "impersonate" the user (which didn't seem to work) or "ensure the user", so I have ended up at this code (which has worked for some people). Can some help explain to me why the following does not work and still gives 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 (SPWe开发者_如何学Cb 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();
}
}
}
Figured it out! Instead of this.Web.Groups
, it is just web.Groups
... I wasn't using the right object.
You have set web.AllowUnsafeUpdates = true;
but didn't set it back.
what you can do in a situation like this is check if SPWeb already does AllowUnsafeUpdates like this.
bool updates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
// do your thing
web.AllowUnsafeUpdates = updates;
This way you set the restrictions back the way it was on it's SPWeb object. In your case I'd would place it in a try catch finally block, where you'd set the web.AllowUnsafeUpdates = updates;
in the finally statement.
If you would run this in your code, it's probably set to true, because you didn't set it back. you can check with SharePoint manager or powershell what the value is of this SPWeb object just to be sure.
精彩评论