如何从受信任的域中获取用户列表?
我试图运行LDAP查询,但我无法从受信任的域获取用户。这是我的代码:
public virtual List<UserModel> SearchUsers(string textValue)
{
var users = new List<UserModel>();
string context;
const string nameProperty = "name";
const string samAccountNameProperty = "samaccountname";
const string distinguishedNameProperty = "distinguishedname";
if (textValue.Contains("(").Equals(true) || textValue.Contains(")").Equals(true) || textValue.Contains("*").Equals(true))
{
textValue = EscapeInvalidCharacters(textValue);
}
var filterForDomainUser ="(&(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(samaccountname=" + textValue + "*)(name=" + textValue + "*)))";
using (HostingEnvironment.Impersonate())
{
using (var root = new DirectoryEntry("LDAP://RootDSE"))
{
context = root.Properties["defaultNamingContext"].Value.ToString();
}
using (var entry = new DirectoryEntry("GC://" + context))
{
using (
var search = new DirectorySearcher(entry,filterForDomainUser,
new[]
{
samAccountNameProperty, nameProperty,
distinguishedNameProperty
}, SearchScope.Subtree))
{
search.ReferralChasing = ReferralChasingOption.All;
search.PageSize = 10;
var resultCol = search.FindAll();
for (var counter = 0; counter < resultCol.Count; counter++)
{
var result = resultCol[counter];
var distinguishedName = (String)result.Properties[distinguishedNameProperty][0];
var domainName =
distinguishedName.Substring(distinguishedName.IndexOf("DC=",
StringComparison
.InvariantCultureIgnoreCase))
.Split(',')[0].Replace("DC=", "");
var name = (String)result.Properties[nameProperty][0];
var samAccountName = string.Format("{0}{1}{2}", domainName, @"\",
result.Properties[samAccountNameProperty][0]);
var userModel = new UserModel
{
DisplayName = name,
UserName = samAccountName
};
users.Add(userModel);
}
}
}
}
//SearchLocalUser(textValue, users);
return users;
}