2012-02-13 43 views
0

我有在Active Directory返回用戶名的Intranet應用的功能:從mycompany.com更改我的域名

public string GetCurrentUsersName() 
    { 
     //Get the username and domain information 
     string user = Environment.UserName; 
     string domainName = Environment.UserDomainName; 

     //Set the correct format for the AD query and filter 
     string ldapQueryFormat = @"LDAP://" + domainName + ".com/DC=" + domainName + ",DC=com"; 
     string queryFilterFormat = @"(&(samAccountName=" + user + ")(objectCategory=person)(objectClass=user))"; 

     SearchResult result = null; 
     using (DirectoryEntry root = new DirectoryEntry(ldapQueryFormat)) 
     { 
      using (DirectorySearcher searcher = new DirectorySearcher(root)) 
      { 
       searcher.Filter = queryFilterFormat; 
       SearchResultCollection results = searcher.FindAll(); 

       result = (results.Count != 0) ? results[0] : null; 
      } 
     } 

     //Get the email property from AD 
     string name = result.Properties["displayName"][0] as string; 
     return name; 
    } 

我最近更改了域名mycompany.local。每當我嘗試運行此方法時,我現在都會收到一個錯誤,我應該更改某些內容嗎?字符串domainName用於等於mycompany,但現在它等於myco,因爲這是我使用的域名。

我收到的錯誤是:

System.Runtime.InteropServices.COMException:服務器不可操作。

回答

1

如果您最近更改域從mycompany.com到mycompany.local爲AD查詢正確的格式和過濾器應該是這樣的:

//Set the correct format for the AD query and filter 
string ldapQueryFormat = @"LDAP://" + domainName + ".local/DC=" + domainName + ",DC=local"; 

與「局部」

+0

你」更換「COM」這個工作正常,但是由於我的服務器仍舊在舊域中,所以出現了一個雙跳問題,所以我不得不使用下面的代碼:using(HostingEnvironment.Impersonate()) {//我的代碼} – CallumVass 2012-02-14 08:07:17

0

是否有理由動態構建域字符串?對於不同的用戶或情況會有所不同嗎?如果沒有,爲什麼不把它定義爲配置設置?您可以從Active Directory獲取您的域的LDAP地址,然後您只需在網站的web.config文件中設置一個靜態設置即可。域名的變化很少,因此設置比設法動態構建更容易。