C# 从计算机上下文获取用户的全名
我有一个ASP.NET应用程序在我们的内部网上运行。在生产环境中,我可以从域上下文中获取用户,并可以访问大量信息,包括他们的名字和姓氏(UserPrincipal.GivenName和UserPrincipal.姓氏) 我们的测试环境不是生产域的一部分,测试用户在测试环境中没有域帐户。因此,我们将它们添加为本地机器用户。当他们浏览到起始页时,系统会提示他们输入凭据。我使用以下方法获取UserPrincipalC# 从计算机上下文获取用户的全名,c#,asp.net,login,userprincipal,C#,Asp.net,Login,Userprincipal,我有一个ASP.NET应用程序在我们的内部网上运行。在生产环境中,我可以从域上下文中获取用户,并可以访问大量信息,包括他们的名字和姓氏(UserPrincipal.GivenName和UserPrincipal.姓氏) 我们的测试环境不是生产域的一部分,测试用户在测试环境中没有域帐户。因此,我们将它们添加为本地机器用户。当他们浏览到起始页时,系统会提示他们输入凭据。我使用以下方法获取UserPrincipal public static UserPrincipal GetCurrentUser(
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或姓氏这样的属性。在创建用户(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和姓氏)