I spent many hours on this very problem. but I ended up with just this change:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new InitializeSimpleMembershipAttribute());
}
}
I had been randomly seeing the following error
System.Web.HttpException (0x80004005): Unable to connect to SQL Server database. ---> System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I noticed that whenever I would see the error I would also see:
at ASP._Page_Views_Shared__Layout_cshtml.Execute() in h:\root\home\btournoux-001\www\site7\Views\Shared_Layout.cshtml:line 5
This happens to be the following line in my _Layout.cshtml:
if (User != null && User.Identity != null && (User.IsInRole("publisher") || User.IsInRole("admin")))
So in order to test my simple solution, I put a breakpoint in my InitializeSmpleMembershipAttribute class at the EnsureInitialized call and another one at the first line in the SimpleMembershipInitializer
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<DataContext>(null);
In addition to those 2 breakpoints I also put a breakpoint in my _Layout.cshtml (I put the test for User in a code section so I could add the breakpoint.
@{
var maintenanceAccess = false;
if (User != null && User.Identity != null && (User.IsInRole("publisher") || User.IsInRole("admin")))
{
maintenanceAccess = true;
}
}
After putting in the breakpoints what I did was to comment out the filters.Add( new InitializSimpleMembershipAttribute() and then start up the app in Visual Studio. I could see that I hit the breakpoint in the _Layout.cshtml before any other breakpoint. Then I uncommented that line and ran the app again. This time I saw the breakpoints inside the InitializeSimpleMembershipAttribute class occur prior to the breakpoint in the _Layout.cshtml. And to be sure it was working correctly, I logged in on my website and then saw the first breakpoint in the InitializeSimpleMembershipAttribute class (EnsureInitialized) but not the second one - which was what I expected.
So it all seems to work.
Thanks to all who discovered this!