asp.net上的active directory用户
本文关键字:directory 用户 active 上的 net asp | 更新日期: 2023-09-27 18:30:13
我想为我们公司使用Active directory创建一个目录intranet网站。到目前为止,我已经得到了这个,但当我在调试模式下运行时,代码在searchResultCollection....search.findAll();
中中断显示:
[DirectoryServicesCOMException(0x80072020):发生操作错误。]
我已尝试将IIS asp.net模拟更改为已启用,但收到HTTP错误500.24。我的用户名具有对Active Directory的读取访问权限。是不是有什么东西我错过了,或者有什么东西可以指引我正确的方向。我到处都找过了,我被卡住了。
提前感谢您的帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.DirectoryServices;
using System.Web.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
GetADUsers();
}
public void GetADUsers()
{
DirectoryEntry myLdap = new DirectoryEntry("LDAP://OU=Nix,DC=systems,DC=com");
DirectorySearcher search = new DirectorySearcher(myLdap);
search.CacheResults = true;
search.SearchScope = SearchScope.Subtree;
search.Filter = "(objectlass=person)";
SearchResultCollection allResults = search.FindAll();
foreach (SearchResult sr in allResults)
{
Response.Write(sr.Properties["name"].ToString());
}
}
您可以使用PrincipalSearcher
和"query-by-example"主体进行搜索:
// 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 "Bruce" and a last name (Surname) of "Miller"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";
qbeUser.Surname = "Miller";
// create your principal searcher passing in the QBE principal
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的文章《在.NET Framework 3.5中管理目录安全主体》,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement
中的新功能。或者,请参阅有关System.DirectoryServices.AccountManagement命名空间的MSDN文档。
当然,根据您的需要,您可能需要在您创建的"示例查询"用户主体上指定其他属性:
DisplayName
(通常为:名字+空格+姓氏)SAM Account Name
-您的Windows/AD帐户名User Principal Name
-您的"username@yourcompany.com"样式名称
您可以在UserPrincipal
上指定任何属性,并将其用作PrincipalSearcher
的"示例查询"。
自我重启后,我再次测试它运行时没有出现错误,然后添加了其余代码以显示在网格视图中。
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
GetADUsers();
}
public void GetADUsers()
{
DirectoryEntry myLdap = new DirectoryEntry("LDAP://OU=Nix,DC=systems,DC=com");
DirectorySearcher search = new DirectorySearcher(myLdap);
search.CacheResults = true;
search.SearchScope = SearchScope.Subtree;
search.Filter = "(objectlass=person)";
SearchResultCollection allResults = search.FindAll();
search.PropertiesToLoad.Add("samaccountname");
Grid1.DataSource = allResults;
Grid1.DataBind();
}