繁体   English   中英

从计算机上下文获取用户全名

[英]Get users full name from Machine Context

我有一个在我们的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时检索UserPrinicipal时,我没有得到GivenName或Surname之类的属性。 创建用户(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属性是DisplayName(而不是GivenName和Surname);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM