Wednesday 5 November 2014

Adding ASP.NET SimpleMembership to an existing MVC 4 application


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. In this blog post I'll try to sum up what you'll need to do to get the simple membership going in your existing projects.
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:
<connectionStrings>
 <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SimpleMembershipTest;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Next you'll have to add the membership provider that points to WebMatrix.WebData.SimpleMembershipProvider:
<membership defaultProvider="SimpleMembershipProvider">
   <providers>
     <clear/>        
         <
add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
   </providers>
 </membership>   
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.CreateRole("Administrator"); 
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.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...