gpt4 book ai didi

c# - 使用 System.DirectoryServices.AccountManagement 时 Active Directory 用户创建延迟

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:32 28 4
gpt4 key购买 nike

我在 .NET 4.5 中使用 System.DirectoryServices.AccountManagement 创建帐户并设置属性。其中一项要求是从模板帐户复制组成员资格(包括主要组)。代码包括以下内容:

foreach (var group in userPrincipal.GetGroups()) {
var groupPrincipal = (GroupPrincipal) @group;

if (groupPrincipal.Sid != templatePrimaryGroup.Sid) {
groupPrincipal.Members.Remove(userPrincipal);
groupPrincipal.Save();
}
}

这在大约 90% 的时间都有效。其余时间,它会失败:

System.DirectoryServices.DirectoryServicesCOMException was
unhandled HResult=-2147016656 Message=There is no such object on
the server.



Source=System.DirectoryServices ErrorCode=-2147016656
ExtendedError=8333 ExtendedErrorMessage=0000208D: NameErr:
DSID-03100213, problem 2001 (NO_OBJECT), data 0, best match of:
'OU=Whatever,DC=domain,DC=local`

GetGroups 调用中。我的猜测是在我下次访问它之前,存在某种竞争条件,用户没有被完全创建。我从诊断日志记录中知道我每次都针对同一个域 Controller (它使用相同的 PrincipalContext 所以符合我的期望)所以这不是复制问题。

我的猜测准确吗?有没有好的方法来处理这个问题?我可以直接加入 Sleep 但这似乎充其量只是一种逃避,而在最坏的情况下则是脆弱的。那么什么是正确的做法呢?

最佳答案

尝试这样的事情:

        int maxWait = 120;
int cnt = 0;
bool usable = false;

while (usable == false && cnt < maxWait)
{
try
{
foreach (var group in userPrincipal.GetGroups())
{
var groupPrincipal = (GroupPrincipal)@group;

if (groupPrincipal.Sid != templatePrimaryGroup.Sid)
{
groupPrincipal.Members.Remove(userPrincipal);
groupPrincipal.Save();
}
}
usable = true;
break;
}
catch
{
System.Threading.Thread.Sleep(500);
}
}
if (usable)
//All okay
;
else
//Do something
;

这样你可以试“一会儿”。如果它运行良好,如果运行不正常,则执行诸如记录错误之类的操作,以便您稍后可以运行修复脚本。

关于c# - 使用 System.DirectoryServices.AccountManagement 时 Active Directory 用户创建延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12716593/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com