System.ArgumentNullException: Value cannot be null. Parameter name: principal

I am working on my Dynamic Data website, or rather web application, in VS 2012 RC, and after reading Dynamic Data Unleashed,, I picked up a few nice tricks, including how to secure your data at the entity level. So, I copied some of the sample code across to my solution, and once everything was building nicely, I started testing the new bits. First access to an entity worked just fine, but any other attempt to access the same entity or any other entity for that resulted in this error:

System.ArgumentNullException: Value cannot be null. Parameter name: principal

Rather annoying, since the sample code worked just fine. It turns out that the methods for checking if the current user is allowed to read a specific entity received a principal that was null. Here is the signature of one of the methods:

public override bool CanRead(IPrincipal principal)

The method is called from another method that checks if a column should be scaffolded/shown to the current user.

private bool IsScaffoldable(MetaColumn column)

This method was calling the CanRead method passing HttpContext.Current.User. This works just fine when you use the ASP.NET Development Server when testing inside Visual Studio. However, if you use IIS Express, it does not work; the error described is consistent. So, I tried the full IIS, but the same thing happened.

It turns out that the issue is with the Integrated pipeline mode, which is new to IIS 7 and later. HttpContext.Current isn’t always available, as you can find more evidence of by Bing’ing it. The solution in my case was to use Thread.CurrentPrincipal instead.