Search code examples
asp.net-mvc-4entity-framework-5membership-provider

You must call the "WebSecurity.InitializeDatabaseConnection"


I have a problem with using [Authorize(Roles = "admin")] attribute.

[Authorize(Roles = "admin")]
    public ActionResult GetAllLocations()
    {

I am getting the following error

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 have built a MVC 4 application using EF 5 Code first with my own database.

A little background:

  • I have created a custom membership provider I have inherited from MembershipProvider

  • I have look at a lot of questions in this site about this issue, but didn't found an answer.

  • In some answers i saw how to disable the membership provider

like this:

    <add key="enableSimpleMembership" value="false"/>
    <add key="autoFormsAuthentication" value="false"/>

This is how i implemented my custom membership provider

 <membership defaultProvider="ATWMembershipProvider">
  <providers>
    <clear/>
    <add name="ATMMembershipProvider" type="AroundTheWorldWeb.Infrastructure.AuthenticationProvider.ATMMembershipProvider"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         equiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5"
         minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10" applicationName="myApplication" />
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
  <providers>
    <remove name="AspNetSqlRoleProvider" />
    <add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <!-- note: WebMatrix registers SimpleRoleProvider with name
     'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
  </providers>
</roleManager>

Solution

  • I fixed this problem by creating the MVC 4 from template. I think there some DLL's aren't loaded when choosing Empty template. So i have created it from a template and override all the Account's methods And also implemented custom member and role provider