2014-09-21 136 views
0

我試圖連接到Active Directory來獲取當前用戶的名稱,但我得到一個錯誤,而不是:錯誤連接到Active Directory

服務器無法聯繫。

代碼:

var identityName = HttpContext.Current.User.Identity.Name; 

using (HostingEnvironment.Impersonate()) 
{ 
    using (var context = new PrincipalContext(ContextType.Domain, "\\MyDomain.local", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer)) 
    using (userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, identityName)) 
    { 
     lblUserName.Text = userPrincipal.DisplayName; 
    } 
} 
+0

我不認爲你應該在你的域名反斜槓 - 試試這個:'新PrincipalContext(ContextType.Domain, 「MyDomain.local」,空, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))' – 2014-09-21 07:49:46

+0

我在它不起作用之前試過了。謝謝,我找到解決方案。 – Anwar 2014-09-21 07:59:13

回答

0
  System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent(); 
     string[] a = Context.User.Identity.Name.Split('\\'); 


     System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]); 
     lblUserName.Text = ADEntry.Properties["FullName"].Value.ToString(); 
+0

但是'WinNT://'提供程序正在使用**機器本地**帳戶 - ***不*** ***活動目錄帳戶.... – 2014-09-21 08:53:10

+0

是的,就像我說的當我發佈web應用程序到iis它的顯示我錯誤「ndex超出了數組的範圍。」但在當地它的工作:( – Anwar 2014-09-21 09:07:17

相關問題