我从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。请帮我。
答案 0 :(得分:1)
更改ApplicationPool
的身份以使用域用户运行。
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.com
或dom\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