如何以编程方式将用户添加到SharePoint组 - 访问被拒绝

时间:2010-06-18 02:05:30

标签: sharepoint

我尝试过尝试使用C#以编程方式将用户添加到SharePoint组(使用非站点管理员)。如果我以网站管理员身份登录,它工作正常......但是,如果我以非网站管理员身份登录,那么我将获得访问被拒绝错误。在做了一些调查之后,我发现我需要“冒充”用户(似乎不起作用)或“确保用户”,所以我最终得到了这个代码(这对某些人有效)。可以帮助我解释一下为什么以下不起作用并仍然给我一个Access is Denied错误?

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();

        }

    }

}

2 个答案:

答案 0 :(得分:3)

想出来!而不是this.Web.Groups,只是web.Groups ......我没有使用正确的对象。

答案 1 :(得分:0)

您已设置web.AllowUnsafeUpdates = true;但未将其设置回来。

在这种情况下您可以做的是检查SPWeb是否已经像这样执行AllowUnsafeUpdates。

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

// do your thing

web.AllowUnsafeUpdates = updates;

这样您就可以按照SPWeb对象的方式设置限制。在你的情况下,我会把它放在try catch finally块中,你可以在finally语句中设置web.AllowUnsafeUpdates = updates;

如果你在代码中运行它,它可能设置为true,因为你没有设置它。您可以使用SharePoint管理器或powershell检查此SPWeb对象的值是什么。

相关问题