从Machine Context获取用户的全名

时间:2009-10-02 16:24:21

标签: c# asp.net login userprincipal

我有一个在我们的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;
        }

我在这里遇到的问题是,当ContextType == Machine我没有获得像GivenName或Surname这样的属性时,会重新启动UserPrinicipal。有没有办法在创建用户时设置这些值(Windows Server 2008),还是需要以不同的方式进行此操作?

1 个答案:

答案 0 :(得分: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的属性是DisplayName(而不是GivenName和Surname);

相关问题