首页 > 解决方案 > 此方法中的执行时间

问题描述

我是 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;
    }

请帮忙!!!

标签: c#asp.netasp.net-core

解决方案


要进行身份验证,我建议改用 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;
            }
        }
    }
}

推荐阅读