我使用以下代码从服务器获取用户的全名:
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配置是否有问题(我怀疑这个)?
答案 0 :(得分:0)
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
基本上,您可以定义域上下文并轻松在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中的用户和群组一起玩!