8

我正在尝试使用Windows登录在ASP.NET MVC 4上创建一个Intranet网站。我已经成功完成了Windows登录。唯一让我困惑的是用部分用户名搜索活动目录。我试图搜索网页和stackoverflow网站,但仍无法找到答案。ASP.NET Active Directory搜索

DirectoryEntry directory = new DirectoryEntry("LDAP://DC=NUAXIS"); 
    string filter = "(&(cn=jinal*))"; 
    string[] strCats = { "cn" }; 
    List<string> items = new List<string>(); 
    DirectorySearcher dirComp = new DirectorySearcher(directory, filter, strCats,  SearchScope.Subtree); 
    SearchResultCollection results = dirComp.FindAll(); 
+0

你能不能给我们讲一讲你用来做在部分用户名搜索代码? – rene 2013-02-21 20:11:27

+0

@rene我已将代码添加到帖子 – 2013-02-21 20:20:44

回答

13

您可以使用PrincipalSearcher和“查询通过例如”主要做你的搜索:

// create your domain context 
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
{ 
    // define a "query-by-example" principal - here, we search for a UserPrincipal 
    // and with the first name (GivenName) of "Jinal*" 
    UserPrincipal qbeUser = new UserPrincipal(ctx); 
    qbeUser.GivenName = "Jinal*"; 

    // create your principal searcher passing in the QBE principal  
    using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser)) 
    { 
     // find all matches 
     foreach(var found in srch.FindAll()) 
     { 
     // do whatever here - "found" is of type "Principal" - 
     // it could be user, group, computer.....   
     } 
    } 
} 

如果您还没有 - 绝对看MSDN文章Managing Directory Security Principals in the .NET Framework 3.5这很好地显示如何充分利用System.DirectoryServices.AccountManagement中的新功能。或者请参阅MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。

当然,这取决于你的需要,你可能想在你创建一个“查询通过例如”用户主体指定其他属性:

  • DisplayName(通常为:第一名称+空格+姓氏)
  • SAM Account Name - 你的Windows/AD帐户名
  • User Principal Name - 你的 “[email protected]” 样式名

可以SPE将UserPrincipal上的任何属性都作为属性,并将它们用作您的PrincipalSearcher的“查询范例”。

+0

谢谢,这有助于很多。 – 2013-02-21 21:32:22

0

您目前的代码是正确的。 我觉得你的通配符倒退了。

考虑一下:

search.Filter = string.Format("(&(sn={0}*)(givenName={1}*)(objectSid=*))", lastName, firstName);