title: System.DirectoryServices.AccountManagement.UserPrincipal - localhost but not iis
body: <p>Why does the code below work fine when I run my web application localhost but not when I install it to an IIS server?</p>
  
  <pre><code>using (HostingEnvironment.Impersonate())
  {
      UserPrincipal activeUser = UserPrincipal.Current;
      String activeUserSid = activeUser.Sid.ToString();
      String activeUserUPN = activeUser.UserPrincipalName;
  }
  </code></pre>
  
  <p>Please don't suggest I stick with <code>HttpContext.Current.User</code> as it doesn't provide access to SID or UPN without additional calls to Active Directory.</p>
  
  <p>The web application will be used by Windows authenticated users from three separate domains, the web server is hosted in a fourth domain. The Application Pool is configured to run under the <code>NetworkService</code> identity and the web app configuration has identity impersonation set to true.</p>
  
  <p>The error message when it runs on IIS is:</p>
  
  <blockquote>
    <p>Error in Page_Load(): UserPrincipal.Current.<br>
    System.InvalidCastException: Unable to cast object of type
    'System.DirectoryServices.AccountManagement.GroupPrincipal' to type
    'System.DirectoryServices.AccountManagement.UserPrincipal'.<br>
    at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext
    context, IdentityType identityType, String identityValue)<br>
    at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()<br>
    at webapp.Details.Default.Page_Load(Object sender, EventArgs e)</p>
  </blockquote>
  
  <p><strong>EDIT</strong>:
  Tried both the following and unfortunately get the same error.
  </p>
  
  <pre><code>UserPrincipal userPrincipal = UserPrincipal.Current;
  Response.Write(userPrincipal.Name);
  </code></pre>
  
  <pre class="lang-cs prettyprint-override"><code>Principal userOrGroup = UserPrincipal.Current;
  Response.Write(userOrGroup.Name);
  </code></pre>