我正在使用 .NET 7 开发 Restful API 项目,我需要能够使用依赖项注入连接到活动目录记录、更新某些属性或创建新记录。
我是 Core 和 MVC 的新手。 惠特 SQL Server 我下载所需的 Nuget 包 Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools, 将连接字符串添加到appsetting.json,创建模型上下文,在program.cs文件中注入服务。 但我不熟悉它是如何工作的,也不熟悉 Active Directory 使用哪些软件包?
我尝试搜索如何连接到Active Directory,但我找到的大多数答案都是关于用户身份验证的,这不是我需要的。并且它没有特定的包或方法来处理更新/插入过程。
对于 AD,而不是 Azure AD,我认为您需要:
System.DirectoryServices
和 System.DirectoryServices.AccountManagement
。
类似这样的:
try
{
string ldapPath = "LDAP://CN=Users,DC=YourDomain,DC=com";
string username = "yourUsername";
DirectoryEntry entry = new DirectoryEntry(ldapPath);
DirectorySearcher searcher = new DirectorySearcher(entry)
{
Filter = $"(SAMAccountName={username})"
};
SearchResult result = searcher.FindOne();
if (result != null)
{
DirectoryEntry userEntry = result.GetDirectoryEntry();
// Update properties
userEntry.Properties["propertyToChange"].Value = "newValue";
// Commit changes
userEntry.CommitChanges();
Console.WriteLine("Update successful");
}
else
{
Console.WriteLine("User not found");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception occurred: {ex.Message}");
}