C# 表单身份验证-FindByIdentity发生操作错误

C# 表单身份验证-FindByIdentity发生操作错误,c#,directoryservices,form-authentication,userprincipal,C#,Directoryservices,Form Authentication,Userprincipal,我有一个表单身份验证: <authentication mode="Forms"> </authentication> <authorization> <deny users="?" /> </authorization> 这很有效。然后我要检查成员组。因此,我要: public static bool IsGroupMember(string username, string sDomain) { List<str

我有一个表单身份验证:

<authentication mode="Forms">
</authentication>
<authorization>
  <deny users="?" />
</authorization>
这很有效。然后我要检查成员组。因此,我要:

public static bool IsGroupMember(string username, string sDomain)
{
    List<string> groupList = new List<string>() {"WebDeveloper", "SyncDeveloper"};
    using (System.Web.Hosting.HostingEnvironment.Impersonate())
    {
        try
        {
            PrincipalContext domain = new PrincipalContext(ContextType.Domain, sDomain);
            UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, username);

            foreach (string groupname in groupList)
            {
                var group = GroupPrincipal.FindByIdentity(domain, groupname);
                if (group != null)
                {
                    if (group.GetMembers(true).Any(member => user.SamAccountName.ToLower() == member.SamAccountName.ToLower()))
                    {
                        return true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ASTools.LogError(ex.ToString());
        }
    }
    return false;
}
我试图补充

using (System.Web.Hosting.HostingEnvironment.Impersonate())
而且

<identity impersonate="true"/>

然后,我尝试将池的标识更改为
NetworkService
LocalSystem
,但没有任何更改。我不明白为什么在我自己的电脑中,即使使用
ApplicationPoolIdentity
,一切都可以正常工作。。 我知道这个问题已经被问过很多次了,但我尝试了我找到的每一个建议,但它们对我不起作用。。
请帮帮我

我必须在
PrincipalContext
中添加用户名和密码:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, username, password);
<identity impersonate="true"/>
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, username, password);