DarthVader
DarthVader

Reputation: 55082

You must call the "WebSecurity.InitializeDatabaseConnection" but I DO

*You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.*

I am getting this error, on and off, randomly and not sure what the reason is. In my route config. Index controller, index action is the default one. and here is the definition:

[Authorize(Roles = "admin")]
[InitializeSimpleMembership]
public class IndexController : Controller

Everytime I restart the application, if i didnt log out, i get the above error. Then I log out and log in again and error disappears.

Why is that happening?

How can i resolve this?

I am using localdb if that would help.

Upvotes: 1

Views: 3401

Answers (1)

Bastaspast
Bastaspast

Reputation: 1040

The problem occurs because the Application_Start() function only triggers on the first user action. But the IndexController is triggered before the user can event perform an action. Just remove the [InitializeSimpleMembership] from your project, It also gave me a lot of frustration...

Just add the following code to your global.asax

private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();

    LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}

public class SimpleMembershipInitializer
{
    public SimpleMembershipInitializer()
    {
        using (var context = new UsersContext())
            context.UserProfiles.Find(1);

        if (!WebSecurity.Initialized)
            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
    }
}

Of course make sure you create the correct dbContext() and have the correct InitializeDatabaseConnections properties set that match your project.

Kr

Upvotes: 4

Related Questions