我有对我们的内联网运行的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中)时设置这些值,或者我需要去了解这个以不同的方式?

有帮助吗?

解决方案

需要修改在原来的问题的功能。如果您尝试访问返回的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的属性是显示名称(而不是给定名称和姓);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top