我有一個Web服務,爲用戶分配用戶名。在裏面我調用了一堆函數,它們驗證在UserPrincipal,samAccountName,proxyaddresses和email字段中的AD中是否存在用戶名。爲什麼principalsearcher代碼顯着較慢
在單元測試中,此代碼需要10秒鐘才能運行。代碼本地部署到Web服務器需要9分鐘才能運行。我不認爲這是第一次運行的問題,因爲它第二次只需要很長時間。我們的域名擁有超過3萬用戶,我必須搜索整個域名以確保名稱不存在。每個需求緩存不能使用,因爲我們需要一個最新的分鐘檢查。
我已經搜索瞭如何提高速度,但還沒有發現任何東西。
任何人都有如何提高性能的建議?
public bool DoesEmailExist(string email)
{
using (var context = GetPrincipalContext())
{
var userQuery = new UserPrincipal(context) { EmailAddress = email + "@*" };
var searcher = new PrincipalSearcher(userQuery);
var result = searcher.FindOne();
if (result == null)
{
var aliasQuery = new ExtendedUserPrincipal(context) { ProxyAddress = "*smtp:" + email + "@*" };
searcher = new PrincipalSearcher(aliasQuery);
var aliasResult = searcher.FindOne();
if (result == null)
{
return false;
}
}
return true;
}
}
private PrincipalContext GetPrincipalContext(string ou)
{
return new PrincipalContext(ContextType.Domain, dc, ou, ContextOptions.Negotiate);
}
編輯 - 我切換到使用的DirectorySearcher和速度似乎有所好轉一些。現在需要5分鐘的時間運行web api。我仍然想知道爲什麼我的單元測試比web api快得多。使用日誌代碼在單元測試中調用DoesUserNameExist需要7秒。通過運行Web API需要5分鐘。
public bool DoesUserNameExist(string userName)
{
string filter = "(|(samAccountName={NAME})(UserPrincipalName={NAME}@*)(mail={NAME}@*)(proxyAddresses=*smtp:{NAME}@*))";
filter = filter.Replace("{NAME}", userName);
using (var de = new DirectoryEntry("LDAP://" + domainController + "/" + rootOU))
{
var searcher = new DirectorySearcher();
searcher.Filter = filter;
searcher.PageSize = 1;
var result = searcher.FindOne();
if (result != null)
{
return true;
}
return false;
}
}