来自Active Directory的UserPrincipal

时间:2012-10-02 14:54:39

标签: c# asp.net active-directory userprincipal

我从Active Directory获取UserPrincipal时遇到问题。首先,我在我的本地环境中使用(不使用IIS而是使用ASP.NET开发服务器):

User usr = new User();
usr.SoeId = Request.ServerVariables["LOGON_USER"];
usr.IP = Request.ServerVariables["REMOTE_ADDR"];
usr.FirstName = UserPrincipal.Current.GivenName;
usr.LastName = UserPrincipal.Current.Surname;

它工作正常。我得到了我想要的东西。但是当我在测试环境中安装应用程序时,我收到错误“对象引用没有设置为对象的实例”。我尝试过来自here的解决方案。

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal up = UserPrincipal.FindByIdentity(pc, usr.SoeId);
    return up.DisplayName;
    // or return up.GivenName + " " + up.Surname;
}

但它不起作用。

我使用Windows身份验证。模拟设置为true。请帮我。

2 个答案:

答案 0 :(得分:1)

更改ApplicationPool的身份以使用域用户运行。

在iis 6中右键单击您的应用程序池,转到Identity选项卡并设置将在其下运行池的域用户。

在iis 7中右键单击您的应用程序池,选择高级设置,在流程模型下找到Identity,将其更改为使用域用户。

您也可以传递域用户并转到PrincipalContest Constructor

using (PrincipalContext context = new PrincipalContext(
                                    ContextType.Domain,
                                    "name of your domain",
                                    "container of your domain",
                                    "user@domain", //create a user in domain for context creation purpose.. this username will be constant.. you can keep it in app config
                                    "password")){
    UserPrincipal up = UserPrincipal.FindByIdentity(pc, usr.SoeId);
    return up.DisplayName;
}

如果您的域名为dom.com,那么您的容器就像DC=dom,DC=com,用户名应该是user@dom.comdom\user

答案 1 :(得分:1)

使用此:

 // find currently logged in user
        UserPrincipal adUser = null;
        using (HostingEnvironment.Impersonate())
        {
            var userContext = System.Web.HttpContext.Current.User.Identity;
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
                ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
            adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
        }

您必须在HostingEnvironment.Impersonate

中包含任何“上下文”调用