2012-07-02 17 views
2

我正在構建一個Intranet應用程序,並且正在使用Windows身份驗證。我有這樣的設置和工作,我通過@ Context.User.Identity.Name.net mvc與Active Directory集成並使用數據模型訪問System.DirectoryServices.AccountManagement

我能看到當前用戶的用戶名,我想查詢Active Directory來檢索顯示名稱,電子郵件地址等

我已經看過System.DirectoryServices.AccountManagement並從此創建了一個基本示例。我不清楚如何在整個應用程序中顯示這些信息。

我至今如下:

public class searchAD 
{ 

    // Establish Domain Context 
    PrincipalContext domainContext = new PrincipalContext(ContextType.Domain); 

    public searchAD() 
    { 
     // find the user 
     UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, HttpContext.Current.User.Identity.Name); 

     if (user != null) 
     { 
      var userGuid = user.Guid; 
      var DisplayName = user.DisplayName; 
      var GivenName = user.GivenName; 
      var EmailAddress = user.EmailAddress; 
     } 

    } 

} 

我假設我需要創建一個視圖模型像這樣?

public class domainContext 
{ 
    public Nullable<Guid> userGuid { get; set; } 
    public string DisplayName { get; set; } 
    public string GivenName { get; set; } 
    public string EmailAddress { get; set; } 
} 

我希望能夠在應用程序的各個部分訪問這些信息。

我沒有收到任何錯誤,只是似乎錯過了將所有這些聯繫在一起的東西。

回答

5

你錯過了Windows標識部分。此外,請記住處置任何AD的對象,你正在使用:

public class AdLookup 
{ 
    public static DomainContext GetUserDetails() 
    { 
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) 
     { 
      IPrincipal principal = HttpContext.Current.User; 
      WindowsIdentity identity = ((WindowsIdentity)principal.Identity); 
      UserPrincipal user = UserPrincipal.FindByIdentity(pc, identity.Name); 

      if (principal != null) 
      { 
       return new DomainContext() { 
        userGuid = user.Guid, 
        DisplayName = user.DisplayName, 
        GivenName = user.GivenName, 
        EmailAddress = user.EmailAddress 
       }; 
      } 
     } 

     return null; 
    } 
} 

的最好的事情左右的時間內您的應用程序創建一個名爲「BaseController」類的所有其他控制器繼承你可以訪問此大家,並將該代碼放在那裏(最好是一個名爲DomainContext的屬性)。

要使用此對所有在你的應用程序,您還可以在主控制器上添加了一個方法,以將此信息添加到的ViewData:

protected override void OnActionExecuted(ActionExecutedContext filterContext) 
{ 
    base.OnActionExecuted(filterContext); 
    ViewData["BaseController_DomainContext"] = AdLookup.GetUserDetails(); 
} 

然後你就可以在任何的從渲染你的看法訪問此這個任何繼承控制器使用:

@{ 
    DomainContext domainContext = (DomainContext)ViewData["BaseController_DomainContext"]; 
} 

Welcome back: @domainContext.DisplayName 

當然你會碰到與空的問題,但你可以處理,在您的GetUserDetails方法與某種虛擬DomainContext的。

這只是一種方法,或者你可以創建一個基本視圖模型,所有視圖模型都從視圖中繼承並直接訪問它們,但是我發現這種方法更簡單,給視圖模型添加任何複雜性。

+0

我試過你以前的代碼,不幸的是沒有工作。你能否澄清如何將DisplayName,GivenName等傳遞給我的View? – Stephen

+0

修改爲更詳細的答案。 – bittenbytailfly

+0

非常感謝。我想我快到了。只是在HttpContext上出錯 - 非靜態字段需要對象引用... – Stephen

相關問題