【发布时间】:2019-02-13 16:18:41
【问题描述】:
我遇到了一个相当令人沮丧的问题。我正在尝试针对 Active Directory 对用户进行身份验证,为此,我将用户变量传递给以下类。
public static ILdapAuthentication CreateInstance(string domainAndUser, string password, string ldapPath)
{
string[] dllPaths = Directory.GetFiles(ExecutingAssemblyDirectory, "*.dll");
List<Assembly> listOfAssemblies = new List<Assembly>();
foreach (var dllPath in dllPaths.Where(x => x.Contains("ActiveDirectoryAuthentication")))
{
Assembly assembly = Assembly.LoadFrom(dllPath);
listOfAssemblies.Add(assembly);
}
Type type = null;
int foundTypes = 0;
foreach (var assembly in listOfAssemblies)
{
type =
assembly.GetTypes()
.FirstOrDefault(x => x.GetInterfaces().Any(i => i == typeof(ILdapAuthentication)));
if (type == null)
continue;
foundTypes++;
}
if (foundTypes == 0)
throw new Exception("ActiveDirectoryAuthentication DLL not found.");
if (foundTypes > 1)
throw new Exception("Only one ActiveDirectoryAuthentication DLL must be used.");
return Activator.CreateInstance(type, domainAndUser, password, ldapPath) as ILdapAuthentication;
}
问题出现在 foreach 循环中,当我尝试获取我的类型时,它总是返回 null,甚至没有点击下面的接口 (ILDPAuthentication) 代码。
public interface ILdapAuthentication
{
bool IsActiveDirectoryUserValid();
}
调用以下代码:
public class LdapAuthentication : ILdapAuthentication
{
private string DomainAndUser { get; set; }
private string Password { get; set; }
private string LdapPath { get; set; }
public LdapAuthentication(string domainAndUser, string password, string ldapPath)
{
this.DomainAndUser = domainAndUser;
this.Password = password;
this.LdapPath = ldapPath;
}
public bool IsActiveDirectoryUserValid()
{
try
{
if (!this.DomainAndUser.Contains('\\'))
throw new Exception("Domain User is invalid.");
string[] userLogin = this.DomainAndUser.Split('\\');
string domain = userLogin[0];
string userName = userLogin[1];
DirectoryEntry entry = new DirectoryEntry(this.LdapPath, this.DomainAndUser, this.Password);
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;
}
else
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
}
初始类在我的名为 ActiveDirectoryAuthentication 的应用程序文件夹中查找我已复制的 DLL。
【问题讨论】:
-
不是答案.. 只是一个建议。查看您对 assembly.GetTypes().. 的 lambda 调用,找出问题所在。不要使用 lambda,这样您就可以看到实际出现的条目。如果您需要深入了解列表,请使用简单的 foreach 循环并使用即时窗口评估条目。我打赌你找到了你的问题。
-
请尽量避免对软件工程师的性别假设,因为这可能不受欢迎。无论如何,我们倾向于减少问候和问候。谢谢。
标签: c# winforms active-directory