如何在moss中获取当前用户组?

时间:2009-12-15 19:06:34

标签: moss

我希望你能解决我的问题。

我正在尝试使用事件处理程序为sharepoint列表和文档库设置项目级别的pemrissions,但我无法做到。请帮助我这是我的代码。我需要根据登录用户为项目分配权限。他属于哪个组。我无法检索当前用户组。这是我的代码。

public override void ItemAdded(SPItemEventProperties properties)
{
  using (SPSite _site = new SPSite(properties.WebUrl))
  {
    using (SPWeb spWeb = _site.OpenWeb(properties.RelativeWebUrl))
    {
      SPUser currentUser = spWeb.CurrentUser;
      SPListItem listItem = properties.ListItem;

      listItem.BreakRoleInheritance(true);
      SPGroupCollection spgroup = currentUser.Groups;

      foreach (SPGroup group in spgroup)
      {
        SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);
        SPRoleDefinition roleDefinition = spWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);

        roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

        listItem.RoleAssignments.Add(roleAssignment);

        spWeb.AllowUnsafeUpdates = true;

        listItem.Update();

        spWeb.AllowUnsafeUpdates = false;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

public override void ItemAdded(SPItemEventProperties properties)
{
  // run the code impersonating the web application account, this works better than the regular RunWithElevatedPrivileges
  using (var site = new SPSite(properties.SiteId, properties.ListItem.ParentList.ParentWeb.Site.SystemAccount.UserToken))
  {
    using (var web = site.OpenWeb(properties.RelativeWebUrl))
    {
      web.AllowUnsafeUpdates = true;
      var item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);

      item.BreakRoleInheritance(false);

      foreach (SPGroup group in web.CurrentUser.Groups)
      {
        var assignment = item.Web.RoleAssignments.GetAssignmentByPrincipal(group);
        var roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);

        assignment.RoleDefinitionBindings.Add(roleDefinition);
        item.RoleAssignments.Add(assignment);
      }

      DisableEventFiring();
      item.SystemUpdate(false);
      EnableEventFiring();
      web.AllowUnsafeUpdates = false;
    }
  }
}