System.DirectoryServices - 伺服器無法執行
我在使用 Windows 身份驗證的網站上收到錯誤消息。
奇怪的事情:
- 僅當使用者尚未保存到數據庫中時才會發生(新的未知使用者)
- 僅在實時系統上出現,在本地開發環境中一切正常
這是我在日誌郵件中得到的:
來源:System.DirectoryServices
消息:伺服器無法執行。
跟踪:
在 System.DirectoryServices.DirectoryEntry.Bind
()
在 System.DirectoryServices.DirectoryEntry.get_AdsObject()
在 System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
在 System.DirectoryServices在 System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) .DirectorySearcher.FindOne ()
在 Smarthouse.Labs.DataAccess.UserListManager.SaveUser(String windowsUserName)
這就是我實現 DirectorySearch 的方式:
private void SaveUser(string windowsUserName) { string[] domainAndUser = windowsUserName.Split('\\'); string domain = domainAndUser[0]; string username = domainAndUser[1]; DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain); DirectorySearcher search = new DirectorySearcher(entry); try { // Bind to the native AdsObject to force authentication. search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); search.PropertiesToLoad.Add("sn"); search.PropertiesToLoad.Add("givenName"); search.PropertiesToLoad.Add("mail"); SearchResult result = search.FindOne(); if (result == null) { throw new Exception("No results found in Windows authentication."); } User userToSave = new User(); userToSave.FirstName = (String) result.Properties["givenName"][0]; userToSave.LastName = (String) result.Properties["sn"][0]; userToSave.Email = (String) result.Properties["mail"][0]; userToSave.Username = windowsUserName; userToSave.Guid = Guid.NewGuid(); SaveUser(userToSave); } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message, ex); } finally { //Dispose service and search to prevent leek in memory entry.Dispose(); search.Dispose(); } }如果需要更多程式碼範例,請告訴我。
您的問題是您使用“普通”域名進行綁定 - 這在 LDAP 中不起作用。實際上,如果您嘗試綁定到
LDAP://MyDomain,您真正要做的是嘗試綁定到名為MyDomain.您需要一個有效的 LDAP 綁定字元串 - 類似的
LDAP://dc=yourdomain,dc=local東西。要找出您的預設 LDAP 綁定上下文是什麼,請使用以下程式碼片段:
DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE"); if (deRoot != null) { string defaultNamingContext = deRoot.Properties["defaultNamingContext"].Value.ToString(); }獲得該字元串後 - 將其用作 LDAP 伺服器的綁定字元串。
如果您使用的是 .NET 3.5 及更高版本,則應查看
System.DirectoryServices.AccountManagement(S.DS.AM) 命名空間。在這裡閱讀所有相關資訊:基本上,您可以定義域上下文並在 AD 中輕鬆找到使用者和/或組:
// set up domain context -- no domain name needed, uses default domain PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username); if(user != null) { // do something here.... }新的 S.DS.AM 使得在 AD 中與使用者和組一起玩變得非常容易!