根据我同事的反馈(感谢 Eirik!)、@KennyZ 的评论和大量的谷歌搜索,我发现这是最好/唯一的方法。作为参考,以及其他看到此问题的人,以下是一些有用的代码,用于从 web.config+connectionStrings.config 中获取 AD 设置,并使用该数据查询 AD 以获取给定用户的显示名称:
var membershipSection = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
var providerSettings = membershipSection.Providers["ActiveDirectoryMembershipProvider"];
var connectionStringName = providerSettings.Parameters["connectionStringName"];
var adUser = providerSettings.Parameters["connectionUsername"];
var adPassword = providerSettings.Parameters["connectionPassword"];
var adConnection = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
var adReference = new DirectoryEntry(adConnection, adUser, adPassword);
var search = new DirectorySearcher(adReference) {Filter = string.Format("(mail={0})", username)};
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
if (result != null)
{
var resultCollection = result.Properties["displayName"];
if (resultCollection.Count > 0)
{
var displayName = resultCollection[0].ToString();
...
}
}
注意:这假设我在 web.config 中使用,userPrincipalName
因为attributeMapUsername
它映射到用户的电子邮件地址。