以下代码仅在IIS中为我们网络上的本地用户启用Windows身份验证时才有效。
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName);
return up;
}
否则会抛出此异常:
[ArgumentException :(&(objectCategory = user)(objectClass = user)(|(userPrincipalName =)(distinguishedName =)(name =)))搜索过滤器无效。 System.DirectoryServices.ResultsEnumerator.MoveNext()+ 434305 System.DirectoryServices.SearchResultCollection.get_InnerList()+282 System.DirectoryServices.SearchResultCollection.get_Count()+9 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(类型principalType,String urnScheme,String urnValue,DateTime referenceDate,Boolean useSidHistory)+1898 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(类型principalType,String urnScheme,String urnValue,DateTime referenceDate)+85 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context,Type principalType,Nullable`1 identityType,String identityValue,DateTime refDate)+211 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context,String identityValue)+95 C:\ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs中的WebApplication1.Index.GetUserPrincipal(String userName):38 C:\ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs中的WebApplication1.Index.Page_Load(Object sender,EventArgs e):19 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,Object o,Object t,EventArgs e)+25 System.Web.UI.Control.LoadRecursive()+ 71 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)+3064
是否有任何方法可以让我们的本地用户使用UserPrincipal 同时启用Windows和匿名身份验证?
答案 0 :(得分:1)
userName
必须是一个空字符串(或者以其他方式,完全由空格组成),显然它不是由FindByIdentity
验证的。
答案 1 :(得分:0)
不确定你是如何让FindByIdentity工作的,因为我认为还需要指定身份类型?即:
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;
}