当前位置: 首页 > 编程语言 > C#

如何在C#Web应用程序中查找用户的ActiveDirectory显示名称?

时间:2023-04-11 11:38:00 C#

如何在C#Web应用程序中找到用户的ActiveDirectory显示名称?我正在编写一个使用Windows身份验证的Web应用程序,我希望使用以下方法获取用户的登录信息:stringlogin=User.Identity.Name.ToString();但我不需要他们的登录名,我需要他们的DisplayName。几个小时以来,我一直在苦苦思索……我可以通过Web应用程序访问我组织的AD吗?这个怎么样:privatestaticstringGetFullName(){try{DirectoryEntryde=newDirectoryEntry("WinNT://"+Environment.UserDomainName+"/"+Environment.UserName);返回de.Properties["fullName"].Value.ToString();}赶上{返回空;请参阅相关问题:ActiveDirectory:检索用户信息另请参阅:如何:(几乎)通过C#在ActiveDirectory中的所有内容,更具体地说,“枚举对象的属性”部分。如果您有指向域中某个组的路径,则以下代码段可能会有所帮助:GetUserProperty("","DisplayName");publicstaticstringGetUserProperty(stringaccountName,stringpropertyName){DirectoryEntryentry=newDirectoryEntry();//"LDAP://CN=,CN=,DC=,DC=,..."entry.Path="LDAP://...";entry.AuthenticationType=AuthenticationTypes.Secure;DirectorySearchersearch=newDirectorySearcher(入口);search.Filter="(SAMAccountName="+accountName+")";search.PropertiesToLoad.Add(propertyName);SearchResultCollection结果=search.FindAll();if(results!=null&&results.Count>0){返回结果[0].Properties[propertyName][0].ToString();}else{返回“未知用户”;}}使用这个:stringdisplayName=UserPrincipal.Current.DisplayName;如果有人关心我设法破解了这个:///这是一些虚构的代码,向您展示如何使用它Session["USER"]=User.Identity.Name.ToString();Session["LOGIN"]=RemoveDomainPrefix(User.Identity.Name.ToString());//不是真正的函数:Dstringldappath="LDAP://your_ldap_path";//"LDAP://CN=,CN=,DC=,DC=,..."Session["cn"]=GetAttribute(ldappath,(string)Session["LOGIN"],"cn");Session["displayName"]=GetAttribute(ldappath,(string)Session["LOGIN"],"displayName");Session["mail"]=GetAttribute(ldappath,(string)Session["LOGIN"],"mail");Session["givenName"]=GetAttribute(ldappath,(string)Session["LOGIN"],"givenName");Session["sn"]=GetAttribute(ldappath,(string)Session["LOGIN"],"sn");///工作代码publicstaticstringGetAttribute(stringldappath,stringsAMAccountName,stringattribute){stringOUT=string.Empty;尝试{DirectoryEntryde=newDirectoryEntry(ldappath);DirectorySearcherds=newDirectorySearcher(de);ds.Filter="(&(objectClass=user)(objectCategory=person)(sAMAccountName="+sAMAccountName+"))";SearchResultCollection结果=ds.FindAll();foreach(SearchResultresultinresults){OUT=GetProperty(result,attribute);}}抓住(异常t){//System.Diagnostics.Debug.WriteLine(t.Message);}返回(OUT!=null)?输出:字符串。空;}publicstaticstringGetProperty(SearchResultsearchResult,stringPropertyName){if(searchResult.Properties.Contains(PropertyName)){returnsearchResult.Properties[PropertyName][0].ToString();}else{返回string.Empty;如果您有兴趣,可以使用LinqtoAD的CodePlex项目“LINQ在UnleashedforC#一书中也有介绍-他使用上述项目作为起点。不隶属于任何一个来源-我最近刚刚阅读了上面的书是《C#学习教程:如何在C#Web应用程序中查找用户的ActiveDirectory显示名称?如果分享的所有内容对您有用,需要进一步了解C#学习教程,希望您多加关注.本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处: