Aspnetmvc 4 and standard dotnet membership and roles
I recently added the aspnet way of handling membership and roles to an experimental site.
One should not write one’s own usr/pwd handling since there are too many places to go wrong.
The MS tutorials all take for granted we want our users in a sqlexpress database situated as app_data in the web project. For most real solutions we want to have the users in a database of our own pick. Pointing aspnet to this one is not hard but has some caveats.
Update your database either through aspnet_regsql.exe found in the dotnet framework folder. This application creates a bunch of stored procedures in the database you chose. If you don’t want everything – say you only want roles and membership but not personalization or schema you have to run aspnet_regsql.exe with parameters. You can also run some scripts to do the same, the same scripts that aspnet_regsql.exe uses.
Then you have to point your site (web.config) to use the database. There is already a default membership provider in machine.config and we want to override it.
Create your ususal connection string.
<configuration> <connectionStrings> <add name="DefaultConnection" connectionString=...;MultipleActiveResultSets=True" /> </connectionStrings> ...
Then to point at it scroll down to (aspnetmvc template has already created it) membership and update. Check the bold for clues.
“Clear” is used for overriding the machine.config value. And since you override it you have to provide a new; that is where “defaultProvider” comes in so set it to the same value as “name”. Finally “connectionStringName” must be equal to your connectionstring’s name as above.
<membership defaultProvider="DefaultMembershipProvider"> <providers> <clear /> <add connectionStringName="DefaultConnection" ... name="DefaultMembershipProvider" ... /> </providers> </membership>
Then you probably want Roles to also be handled in your own database so do the same for “roleManager”.
All this can be found on the web but I spent an hour on it so I thought I’d jot it down for future googling.