My problem with SimpleMembership, MVC4 and AuthorizeAttribute and Roles

I have created an internet application using the MVC4 template with SimpleMembership.

It comes with a “InitializeSimpleMembershipAttribute” which initialize (create) the database if it is not exist. The InitializeSimpleMembershipAttribute attribute is added to the account controller.

Now if I put [Authorize] or [Authroize(Users=”administrator”)] in action method. When I direct to the URL, it gives me an error:

Server Error in ‘/’ Application.

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)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

SQLExpress database file auto-creation error:

The connection string specifies a local Sql Server Express instance using a database location within the application’s App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:

I spent quite a bit of time figuring out this. What I did is, putting the line “WebSecurity.InitializeDatabaseConnection” to the Global.asax file. That ensures the database connection is initialized as early as possible.

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

Then I move the filter from AccountController to the FilterConfig.cs file. So when the filters are registered, it calls the InitializeSimpleMembershipAttribute as well.

filters.Add(new InitializeSimpleMembershipAttribute());

I hope this may help people who is having the same problem.