我不确定为什么会发生这种情况,但当我运行这段代码时,它可以在一台服务器上运行,但在另一台服务器上就不行了。
两台服务器都返回正确的found.DisplayName,但是只有一台服务器返回oUserPrincipal的值,另一台服务器返回空值。
错误行:
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName) returns null
dynamic config = _getExpandoFromXml("config.xml");
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.activeDirectory.sDomain, config.activeDirectory.sDefaultOU,config.mailServer.user, config.mailServer.pass);
UserPrincipal user = new UserPrincipal(ctx);
PrincipalSearcher search = new PrincipalSearcher(user);
Console.WriteLine("before foreach");
foreach (Principal found in search.FindAll())
{
try{
if (found.DisplayName == null)
{
Console.WriteLine("found.Dispalyname is null");
}
else
{
Console.Write("Dispalyname: ");
Console.WriteLine(found.DisplayName);
}
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName);
Console.Write("looking for user: ");
Console.WriteLine(found.DisplayName);
Console.WriteLine("after findbyidentiy");
if (oUserPrincipal == null)
{
Console.WriteLine("oUserPrinciapal is null");
}
if (oUserPrincipal.LastPasswordSet == null)
{
Console.WriteLine("lastpasswordset is null");
}
DateTime? dateOrNull = oUserPrincipal.LastPasswordSet;
Console.WriteLine("after LastPasswordSet");发布于 2013-03-14 06:19:51
FindByIdentity只能搜索少数几个属性。它们是“IdentityType枚举中包含的任何格式”。
Name是一个有效的选项,但是没有列出DisplayName,因此您可能会得到DisplayName和Name恰好相同的结果,否则将失败。
使用:
var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.Name);或
var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.SamAccountName);应该行得通。
还有一个three parameter version of FindByIdentity,允许您指定要搜索的属性。
发布于 2016-11-10 02:23:40
在我的例子中,我发现问题是它没有连接到AD服务器。如果我将鼠标悬停在oPrincipalContext上,它的ConnectedServer属性显示它抛出了一个System.DirectoryServices.DirectoryServicesCOMException类型的异常。如果发生这种情况,则应重新启动域控制器上的服务。我们发现这可能发生在高登录时间,因为我们的开发网络上只有1个DC。

https://stackoverflow.com/questions/15397417
复制相似问题