c# - 此方法中的执行时间
问题描述
我是 ASP.NET 的新手,所以我有一个代码需要优化它并使其更快,因为它需要很长时间才能执行。这需要时间的部分:
public bool IsAuthenticated(String domain, String username, String pwd)
{
img = null;
String domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{//Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
if (result.Properties["cn"].Count > 0)
_userName = _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
请帮忙!!!
解决方案
要进行身份验证,我建议改用 PrincipalContext。
(此代码正在生产中)
namespace Contoso.Security
{
internal class LDAPService : ILDAPService
{
private readonly ILogger<LDAPService> _logger;
public LDAPService(ILogger<LDAPService> logger)
{
_logger = logger;
}
public bool ValidateCredentials(string domain, string user, string password)
{
try
{
using PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain, "ou=ADAM Users,O=Microsoft,C=US");
return domainContext.ValidateCredentials(user, password, ContextOptions.Negotiate);
}
catch (Exception ex)
{
_logger.LogCritical(ex,ex.Message);
return false;
}
}
}
}
推荐阅读
- google-cloud-platform - 为什么我无法访问 GCP 活动云 shell?
- c# - 消除字符串中的空格
- node.js - 在引用具有不同本地字段的同一表的聚合中使用两个“查找阶段”
- python - SQLAlchemy 加入关联表
- python - 添加 CSS 文件后出现黑屏
- php - PHP7.3:如何在不在子类中重新声明的情况下,继承具有最大可能范围的受保护静态属性?
- mysql - 根据项目从两个 sql 表中求和和差异 - laravel
- css - 在 Safari 中垂直拉伸的图像,父容器作为 display flex
- c++ - 我应该将结构用作 C++ 中的参数化构造函数吗?
- android - 如何为电子商务 Android 应用程序制作管理面板或管理应用程序