【发布时间】:2009-12-02 14:44:38
【问题描述】:
帮助!我一直在尝试编写一个函数来确认用户在 Active Directory 组中的成员身份,如果该成员恰好在该组中,它会起作用,但如果用户不在,它会引发异常。
函数如下:
private bool IsUserMemberOfGroup(string user, string group)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
{
if (groupPrincipal == null)
{
return false;
}
else
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
}
这里是 YSOD:
“/”应用程序中的服务器错误。
未知错误(0x80005000)
说明:在执行当前 Web 请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详情:
System.Runtime.InteropServices.COMException:未知错误 (0x80005000)
来源错误:
Line 34: else
Line 35: {
Line 36: return userPrincipal.IsMemberOf(groupPrincipal);
Line 37: }
Line 38: }
我不知道它是否相关,但是当我单步执行该函数时,groupPrincipal.Members.Count 抛出“System.NullReferenceException”类型的异常,Count.Base 显示异常消息“对象引用不设置为对象的实例”。
这到底是怎么回事?当某人不是成员时,为什么名为 IsMemberOf 的布尔值不会返回 false?
谢谢,
丹尼尔
【问题讨论】:
-
什么是“用户”和“组”??
-
抱歉,这些是(例如)“domain\\user_SAMAccountName”和“domain\\group_SAMAccountName”。