Even though there is an MVC 4 template for a new Internet project that contains membership functionality, some people like to start building their apps from an empty project.

There is a great blog post by Jon Galloway that explains the new simple membership in detail.

We can start by creating the database which I named “SimpleMembershipTest”. After that, I created a new MVC 4 project using the “Empty” template.

The next step is to add references to WebMartix.Data and WebMatrix.WebData which is shown in Image 1.


After you have added those, expand “References” in your Solution Explorer and go to properties of both of them by right clicking on each. In the properties window set “Copy Local” to True as shown in Image 2.


In the Web.config you’ll have to add the connection string. I was using SQLEXPRESS database so my ConnectionString looks like this:

    <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SimpleMembershipTest;Integrated Security=True" providerName="System.Data.SqlClient" />

Next you’ll have to add the membership provider that points to WebMatrix.WebData.SimpleMembershipProvider:

<membership defaultProvider="SimpleMembershipProvider">
        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>

Now enable the role manager:

<roleManager enabled="true" />

Finally, in Global.asax.cs - Application_Start() method we have to initialize the membership system by calling WebSecurity.InitializeDatabaseConnection

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

After that we can create our user, add a role, add the user to the role and more:

WebSecurity.CreateUserAndAccount("Admin", "Admin");             
Roles.AddUserToRole("Admin", "Administrator");

After running the application, our membership tables are created which can be seen in Image 3.


And that’s it! On your next application start, the table “UserProfile” will be created along with the rest of the SimpleMembership tables. From there you can build your own Registration and Login with the help of the functionality that System.Web.Security.Roles and WebMatrix.WebData.WebSecurity provide.

More articles