System.DirectoryServices.AccountManagement.UserPrincipal - localhost but not iis

Why does the code below work fine when I run my local web application, but not when I install it on the IIS server?

using (HostingEnvironment.Impersonate()) { UserPrincipal activeUser = UserPrincipal.Current; String activeUserSid = activeUser.Sid.ToString(); String activeUserUPN = activeUser.UserPrincipalName; } 

Please do not suggest me stick with HttpContext.Current.User , as it does not provide access to SID or UPN without additional calls to Active Directory.

The web application will be used by authenticated Windows users from three separate domains, the web server is located in the fourth domain. The application pool is configured to work under the NetworkService identifier, and the identity of the personification of authenticity is set in the configuration of the web application.

Error message when starting up in IIS:

Error in Page_Load (): UserPrincipal.Current.
System.InvalidCastException: Cannot reset an object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to enter a type of 'System.DirectoryServices.AccountManagement.UserPrincipal.
in System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity (PrincipalContext context, IdentityType identityType, String identityValue)
in System.DirectoryServices.AccountManagement.UserPrincipal.get_Current ()
in webapp.Details.Default.Page_Load (object sender, EventArgs e)

EDIT : I tried the following, and unfortunately I got the same error.

 UserPrincipal userPrincipal = UserPrincipal.Current; Response.Write(userPrincipal.Name); 
 Principal userOrGroup = UserPrincipal.Current; Response.Write(userOrGroup.Name); 
+7
source share
3 answers

It seems like some other method is needed to define the user.
Here is a description from msdn for the property:
"Gets the user main object that represents the current user the thread is running under."
Thus, UserPrincipal.Current returns a user running IIS.

http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx

+1
source

I had a lot of problems deploying UserPrincipal.Current and still don't quite understand why.

Finally, I ended up using PrincipalSearcher and created the following function to do what I thought about how UserPrincipal.Current works.

 private UserPrincipal GetActiveDirectoryUser(string userName) { using(var ctx = new PrincipalContext(ContextType.Domain)) using(var user = new UserPrincipal(ctx) { SamAccountName = userName}) using(var searcher = new PrincipalSearcher(user)) { return searcher.FindOne() as UserPrincipal; } } 

And I passed System.Web.HttpContext.Current.User.Identity.Name to this method as userName.

+3
source

Yes, this is because you are getting rid of the returned UserPrincipal object due to reusing operators. Remove 'ctx' from the using statement, and then the callers are responsible for deleting the returned object.

0
source

All Articles