使用C#从Active Directory获取全名;部署后无法工作
本文关键字:部署 工作 全名 Active Directory 获取 使用 | 更新日期: 2023-09-27 18:24:54
我使用以下代码从服务器获取用户的全名:
public string getUserName(int empID)
{
DirectoryEntry objDirectoryEntry = new DirectoryEntry("LDAP://SOMEDOMAIN.com");
objDirectoryEntry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher objDirectorySearch = new DirectorySearcher(objDirectoryEntry);
objDirectorySearch.Filter = "(SAMAccountName=" + empID + ")";
objDirectorySearch.PropertiesToLoad.Add("displayName");
SearchResult objSearchResult = objDirectorySearch.FindOne();
if (objSearchResult != null)
return Convert.ToString(objSearchResult.Properties["displayname"][0]);
else
return "User not found";
}
这在我的本地机器上运行得非常好。
然而,在将其部署到服务器之后,它根本不起作用。
这将返回NULL。
正如@marc_s建议的那样,我尝试使用以下代码:
public string getUserStackExchange(string empID)
{
string fullName = empID;
// set up domain context using the default domain you're currently logged in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, empID);
/* or if you're interested in the *currently logged in* user,
then you could also use:
UserPrincipal user = UserPrincipal.Current;
*/
if (user != null)
{
// get the "DisplayName" property ("Fullname" is WinNT specific)
fullName = user.DisplayName;
// do something here....
}
}
return fullName;
}
同样的结果。在本地工作非常好。但部署后就不起作用了。然而,如果我在调试模式下运行项目并打开断点,它会完美地获取数据。
代码或IIS配置是否有问题(我怀疑是这样)?
如果您使用的是.NET 3.5及更高版本,则应该检查System.DirectoryServices.AccountManagement
(S.DS-AM)命名空间。点击此处阅读:
- System.DirectoryServices.AccountManagement上的MSDN文档
基本上,您可以定义域上下文,并在AD:中轻松找到用户和/或组
// set up domain context using the default domain you're currently logged in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
/* or if you're interested in the *currently logged in* user,
then you could also use:
UserPrincipal user = UserPrincipal.Current;
*/
if(user != null)
{
// get the "DisplayName" property ("Fullname" is WinNT specific)
string fullName = user.DisplayName;
// do something here....
}
}
新的S.DS.AM让在AD中与用户和组一起玩变得非常容易!