Adding ASP.NET SimpleMembership to an existing MVC 4 application
Development | Dalibor Mesaric

Adding ASP.NET SimpleMembership to an existing MVC 4 application

Tuesday, May 7, 2013 • 1 min read
Even though there is an MVC 4 template that contains membership functionality, there are scenarios in which you will want to start from scratch. This article explains how to add SimpleMembership infrastructure to an existing project.

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.