2009-10-02 78 views
2

我有一個在我們的Intranet上運行的ASP.NET應用程序。在生產中,我可以從域上下文獲取用戶,並可以訪問許多信息,包括他們的名字和姓氏(UserPrincipal.GivenName和UserPrincipal.Surname)。從機器上下文獲取用戶全名

我們的測試環境不是生產域的一部分,測試用戶在測試環境中沒有域帳戶。所以,我們將它們添加爲本地機器用戶。當他們瀏覽到開始頁面時,系統會提示他們輸入憑據。我用下面的方法來獲取UserPrincipal

public static UserPrincipal GetCurrentUser() 
     { 
      UserPrincipal up = null; 

      using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) 
      { 
       up = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
      } 

      if (up == null) 
      { 
       using (PrincipalContext context = new PrincipalContext(ContextType.Machine)) 
       { 
        up = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
       } 
      } 

      return up; 
     } 

我這裏的問題是,當UserPrinicipal被retrived當ContextType ==機我沒有得到這樣給定名稱或姓名性能。有沒有辦法在創建用戶時設置這些值(Windows Server 2008)還是需要以其他方式來解決這個問題?

回答

4

原始問題中的功能需要修改。如果您嘗試訪問返回的UserPrincipal對象,你會得到一個的ObjectDisposedException

此外,User.Identity.Name不可用,需要傳遞。

我已經做了如下修改上面的功能。

public static UserPrincipal GetUserPrincipal(String userName) 
     { 
      UserPrincipal up = null; 

      PrincipalContext context = new PrincipalContext(ContextType.Domain); 
      up = UserPrincipal.FindByIdentity(context, userName); 

      if (up == null) 
      { 
       context = new PrincipalContext(ContextType.Machine); 
       up = UserPrincipal.FindByIdentity(context, userName); 
      } 

      if(up == null) 
       throw new Exception("Unable to get user from Domain or Machine context."); 

      return up; 
     } 

此外,我需要使用UserPrincipal的屬性是顯示名稱(而不是給定名稱和姓);