Asp.net-Mvc-4

ASP.NET 活動目錄搜尋

  • April 2, 2014

我正在嘗試使用 Windows 登錄在 ASP.NET MVC 4 上創建一個 Intranet 網站。我已經成功完成了windows登錄。我唯一堅持的是使用部分使用者名搜尋活動目錄。我嘗試搜尋 web 和 stackoverflow 網站,但仍然找不到答案。

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

您可以使用 aPrincipalSearcher和“按範例查詢”主體進行搜尋:

// 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,它很好地展示瞭如何充分利用 .NET Framework 中的新功能System.DirectoryServices.AccountManagement。或查看System.DirectoryServices.AccountManagement命名空間上的 MSDN 文件。

當然,根據您的需要,您可能希望在您創建的“範例查詢”使用者主體上指定其他屬性:

  • DisplayName(通常:名字 + 空格 + 姓氏)
  • SAM Account Name- 您的 Windows/AD 帳戶名稱
  • User Principal Name- 您的“username@yourcompany.com”樣式名稱

您可以在 上指定任何屬性UserPrincipal並將其用作PrincipalSearcher.

引用自:https://stackoverflow.com/questions/15011291