2013-03-13 110 views
4

以下代碼僅適用於IIS中爲本地用戶啓用了Windows身份驗證的情況。使用Windows身份驗證和匿名身份驗證獲取UserPrincipal

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
{ 
    UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName); 
    return up; 
} 

否則引發此異常:

[ArgumentException的:將(&(objectCategory =用戶)(objectClass的=用戶)(|(的UserPrincipalName =)(的distinguishedName =)(名稱=)) )搜索過濾器是無效的。] System.DirectoryServices.ResultsEnumerator.MoveNext()434305 System.DirectoryServices.SearchResultCollection.get_InnerList()282 System.DirectoryServices.SearchResultCollection.get_Count()9 System.DirectoryServices.AccountManagement。 ADStoreCtx.FindPri ncipalByIdentRefHelper(類型principalType,字符串urnScheme,字符串urnValue,日期時間referenceDate,布爾useSidHistory)1898 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(類型principalType,字符串urnScheme,字符串urnValue,日期時間referenceDate)85 System.DirectoryServices.AccountManagement .Principal.FindByIdentityWithTypeHelper(PrincipalContext上下文,類型principalType,Nullable`1標識類型,字符串identityValue,DateTime refDate)+211 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext上下文,String identityValue)+95 WebApplication1.Index.GetUserPrincipal字符串userName)在C:\ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs中:38 WebApplication1.Index.Page_Load(Object sender,EventArgs e)in C:\ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs: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(布爾includeStagesBeforeAsyncPoint,布爾includeStagesAfterAsyncPoint)3064

有沒有得到這個工作對於任何方式讓我們的本地用戶UserPrincipal 而Windows和匿名身份驗證均爲開啓?

回答

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; 
    } 
1

userName必須是一個空字符串(或以其他方式,完全由空白的),顯然它不是由FindByIdentity驗證。