C# 在上获取具有Windows身份验证和匿名身份验证的UserPrincipal

C# 在上获取具有Windows身份验证和匿名身份验证的UserPrincipal,c#,asp.net,.net,iis-7.5,userprincipal,C#,Asp.net,.net,Iis 7.5,Userprincipal,以下代码仅在IIS中为网络上的本地用户启用Windows身份验证时有效 using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName); return up; } 否则会引发此异常: [ArgumentException:(&(objectCategory=user)

以下代码仅在IIS中为网络上的本地用户启用Windows身份验证时有效

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
     UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName);
     return up;
}
否则会引发此异常:

[ArgumentException:(&(objectCategory=user)(objectClass=user)(|(userPrincipalName=)(DifferentizedName=)(name=))搜索筛选器无效。] System.DirectoryServices.ResultsEnumerator.MoveNext()+434305 System.DirectoryServices.SearchResultCollection.get_InnerList()+282 System.DirectoryServices.SearchResultCollection.get_Count()+9 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(类型principalType,字符串urnScheme,字符串urnValue,日期时间引用日期,布尔useSidHistory)+1898 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(类型principalType,字符串urnScheme,字符串urnValue,日期时间referenceDate)+85 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext上下文,键入principalType,可空`1 identityType,String identityValue,DateTime refDate)+211 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext上下文,字符串标识符值)+95 C:\Users\xxx\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\Index.aspx.cs:38中的WebApplication1.Index.GetUserPrincipal(字符串用户名) WebApplication1.Index.Page\u在C:\Users\xxx\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\Index.aspx.cs中加载(对象发送方,事件参数e):19 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,对象o,对象t,事件参数e)+25 System.Web.UI.Control.LoadRecursive()+71 System.Web.UI.Page.ProcessRequestMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)+3064


当Windows和匿名身份验证都处于打开状态时,是否有办法让本地用户UserPrincipal使用此功能?

不确定您是如何获得FindByIdentity的,因为我认为还需要指定身份类型?i、 e:

UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);
无论哪种方式,如果您强制进行模拟,模拟可能会起作用。因此,在该代码段之前,请使用以下命令:

// This will impersonate the logged in user in order to get whichever username you require GIVEN the logged in user has AD read/querying rights.

System.Web.HttpContext.Current.Request.LogonUserIdentity.Impersonate();
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
    UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName);
    return up;
    }

userName
必须是一个空字符串(或者以其他方式,完全由空格组成),显然它没有通过
FindByIdentity
验证