2009-10-02 46 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的属性是显示名称(而不是给定名称和姓);