title: "Safe handle has been closed" on per-user caching in ASP.NET MVC 3
body: <p>I'm developing an intranet where I store data using the System.Web.Caching.Cache implementation of caching.
  I can't seem to get around the "Safe handle has been closed" error, that is produced with the following stacktrace:</p>
  
  <pre><code>[ObjectDisposedException: Safe handle has been closed]
   System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean&amp; success) +0
   Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32&amp; ReturnLength) +0
  System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) +203
  System.Security.Principal.WindowsIdentity.get_User() +94
  System.Security.Principal.WindowsIdentity.GetName() +127
  System.Security.Principal.WindowsIdentity.get_Name() +42
  </code></pre>
  
  <p>The error is generated at the following line:</p>
  
  <pre><code>@if(intranet.Models.NyhederModels.isAdministrator(CachedVariables.getWP(User)))
  </code></pre>
  
  <p>Where getWP is as follows:</p>
  
  <pre><code>public static WindowsPrincipalEx getWP(System.Security.Principal.IPrincipal User)
  {
      Cache context = HttpRuntime.Cache;
      WindowsPrincipalEx wp = context["windowsPrincipal_" + User.Identity.Name] as WindowsPrincipalEx;
      if (wp == null)
      {
           wp = new intranet.Models.WindowsPrincipalEx(User.Identity);
          context.Insert("windowsPrincipal_" + User.Identity.Name, wp, null, DateTime.Now.AddSeconds(15.0), Cache.NoSlidingExpiration);
      }
      return wp;
  }
  </code></pre>
  
  <p>As you can see, the key into the cache takes the UserPrincipal, to make sure the cached data is on a per-user basis. I tried using HttpContext.Current, where the caching partially works, but since this happens on a per-request basis, the data is still retrieved once for every page.</p>
  
  <p>The above code works flawlessly on the localhost but shows the "Safe handle has been closed" when run in production environment.</p>
  
  <p>The data being cached is the result of a query into Windows Active Directory, if that makes any difference and User is an instance of System.Security.Principal.IPrincipal.</p>
  
  <p>Any thoughts on this error, which only appeared after introducing the caching?</p>
  
  <p>Thank you in advance</p>