如何从ASP.NET C#应用程序中筛选Active Directory中的特定组

时间:2018-08-28 21:24:51

标签: c# asp.net active-directory

以下代码用于获取我的广告中列出的所有用户。现在,我需要将结果限制为一组。如何修改以下内容以仅获取Active Directory中“每个人”组的成员?

后面的代码:

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.AddRange(new DataColumn[4]
        {
            new DataColumn("givenName", typeof (string)),
            new DataColumn("sn", typeof (string)),
            new DataColumn("mail", typeof (string)),
            new DataColumn("department", typeof (string))
        });

        using (var context = new PrincipalContext(ContextType.Domain, null))            
        {
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                foreach (var result in searcher.FindAll())
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                    var clsuser = new ClsUsers();
                    dt.Rows.Add
                    (
                        Convert.ToString(de.Properties["givenName"].Value), 
                        Convert.ToString(de.Properties["sn"].Value),
                        Convert.ToString(de.Properties["mail"].Value),
                        Convert.ToString(de.Properties["department"].Value)
                    );
                }

                grdvList.DataSource = dt;
                grdvList.DataBind();
            }
        }
    }

这是正在填充的gridview:

<asp:GridView ID="grdvList" runat="server" AutoGenerateColumns="False" >
    <Columns>
        <asp:BoundField DataField="givenName" HeaderText="GivenName" ReadOnly="True" />
        <asp:BoundField DataField="sn" HeaderText="sn" ReadOnly="true" />                    
        <asp:BoundField DataField="mail" HeaderText="Email" ReadOnly="true" />
        <asp:BoundField DataField="department" HeaderText="Department" ReadOnly="true" />
    </Columns> 
</asp:GridView>

我尝试通过更改上下文变量以指定“ Everybody”来稍微修改代码,但出现错误: 尝试代码mod:

using (var context = new PrincipalContext(ContextType.Domain, null, "CN=Everybody", "DC=mydomain", "DC=org"))

这是错误:

  

System.DirectoryServices.AccountManagement.PrincipalOperationException:'发生了本地错误。

1 个答案:

答案 0 :(得分:0)

在看了SO上的其他十二个线程之后,我今天早晨偶然发现了一个回答了我问题的问题……Get Members of an AD Group