I have problem with getting UserPrincipal from Active Directory. First of all I have used on my local environment (using not IIS but ASP.NET development Server):
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;
And it works fine. I got what I want. But when I install application on testing environment I got error "Object reference not set to an instance of an object". I have tried solution from here.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, usr.SoeId);
return up.DisplayName;
// or return up.GivenName + " " + up.Surname;
}
But it does not work.
I use windows authentication. Impersonation is set to true. Please help me.
change the identity of your ApplicationPool
to run using domain user.
in iis 6 right-click your application pool, go to Identity
tab and set a domain user under which the pool will run.
in iis 7 right-click your application pool, select advance settings, under process model you'll find Identity
, change it to use domain user.
you can also pass a domain user and pass to 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;
}
if your domain name is dom.com
then your container would be something like DC=dom,DC=com
and the user name should be given as [email protected]
or dom\user