我有一个可以发送电子邮件的应用程序。现在要求使用 ldap 来验证用户电子邮件。我对这个概念很陌生。我已获得一个 ldap
服务器链接。不知道如何继续。任何文章或点击都会非常有帮助。
这是我正在尝试的代码
public static UserDetail GetUserDetails(string EmailId, string domainName)
{
UserDetail userDetail = new UserDetail();
try
{
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", EmailId);
string[] properties = new string[] { "fullname" };
DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domainName, null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
SearchResult result = searcher.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();
string displayName = directoryEntry.Properties["displayName"[0].ToStrin();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string emailId = directoryEntry.Properties["mail"][0].ToString();
userDetail.EmailId = emailId;
}
catch (Exception)
{
}
return userDetail;
}
我想通过单击搜索按钮来实现它。如何调用方法并传递变量。
最佳答案
如果您使用的是 .NET 3.5 或更高版本,则可以使用 PrincipalSearcher
和“按示例查询”主体进行搜索:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the e-mail of "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09282859395b09588919d809c95de939f9d" rel="noreferrer noopener nofollow">[email protected]</a>"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.EmailAddress = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e1f1f6e0e6c3e6fbe2eef3efe6ade0ecee" rel="noreferrer noopener nofollow">[email protected]</a>";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// try to find that user
UserPrincipal found = srch.FindOne() as UserPrincipal;
if(found != null)
{
// do whatever here - "found" is the user that matched the e-mail given
}
else
{
// there wasn't any user with that e-mail address in your AD
}
如果您还没有阅读过 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或者参见MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。
当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:
显示名称
(通常:名字 + 空格 + 姓氏)SAM 帐户名称
- 您的 Windows/AD 帐户名称用户主体名称
- 您的“[email protected] ”样式名称
您可以在 UserPrincipal
上指定任何属性,并将这些属性用作 PrincipalSearcher
的“示例查询”。
关于c# - .net C# 中的 LDAP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949421/