Get full username from Machine Context

I have an ASP.NET application running on our intranet. In production, I can get the user out of the domain context and access a lot of information including their first and last name (UserPrincipal.GivenName and UserPrincipal.Surname).

Our test environment is not on a production domain, and the test users do not have domain accounts in the test environment. So we add them as local computer users. They will be prompted for their credentials when they go to the start page. I am using the following method to get the 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;
        }

      

The problem I am having here is that when UserPrinicipal is fetched when ContextType == Machine, I am not getting properties like GivenName or Surname. Is there a way to set these values ​​when creating a user (Windows Server 2008) or do I need to do this differently?

+2


source to share


1 answer


The function in the original question needs to be changed. If you try to access the returned UserPrincipal object you will get ObjectDisposedException

Also, the username .Identity.Name is not available and must be passed.

I have made the following changes to the above function.



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;
        }

      

Also, the UserPrincipal property I need to use is DisplayName (instead of first and last name);

+4


source







All Articles