SimpleMembership.Mvc3 NuGet Package
SimpleMembership.Mvc3 – 1.0
Enables the SimpleMembership API from WebMatrix/WebPages (i.e. WebSecurity) to be used with ASP.NET MVC3. This allows you to use the WebSecurity helper found in the WebMatrix.WebData namespace.
Update: February 28, 2011 – Version 1.0 released
This includes:
- The App_Start convention from David Ebbo’s post.
- An updated dependency on WebActivator 1.3.2 or greater (This allows us to use the new PostApplicationStartMethod in WebActivator which allows us to remove the need to modify global.asax.cs).
- Removed need to modify global.asax.cs
- Now, the call to WebSecurity.InitializeDatabaseConnection() is in the new Post App Startup method called Initialize() inside App_Start/SimpleMembershipMvc3.cs. This is where you’ll need to specify your connection string and user table.
Features
- Includes a web activator and web.config transforms that enable the SimpleMembershipProvider
- Includes an abstraction of the WebSecurity helper (IWebSecurityService) and an implementation (WebSecurityService) to enable use with DI/IoC frameworks such as NInject, etc.
Usage

- Modify the Initialize() method in App_Start/SimpleMembershipMvc3.cs to point to your connection string and user table.
- That’s It!
Using the IWebSecurityService abstraction
This package includes an abstraction of the WebSecurity interface (Services/IWebSecurityService) as well as an implementation of this interface (Services/WebSecurityService). This is useful for scenarios like using WebSecurity with Ninject or another IoC/DI framework to avoid hard references to WebSecurity and improve testability. To use this:
- First, make sure you register WebSecurityService as an IWebSecurityService with your IoC container.
- Next, remove the call to WebSecurity.InitializeDatabaseConnection from the Initialize() method in App_Start/SimpleMembershipMvc3.cs
- Finally, uncomment the following lines and modify the call to InitializeDatabaseConnection() to point to your connection string and user table:
var webSecurityService = DependencyResolver.Current.GetService<IWebSecurityService>(); webSecurityService.InitializeDatabaseConnection(connectionStringName: "Default", userTableName: "Users", userIdColumn: "ID", userNameColumn: "Username", autoCreateTables: true);
Currently, the package includes the actual WebMatrix.WebData.dll assembly. I’m looking into changing the package to instead use powershell to add the reference to the project if it already exists on the user machine.
Enjoy!
Adam

about 2 years ago
That line of code that needs to be written to set up this package should be done using webactivator. Take a look at this blog post http://blogs.msdn.com/b/davidebb/archive/2010/10/11/light-up-your-nupacks-with-startup-code-and-webactivator.aspx
about 2 years ago
David,
Thanks for the link. I tried using WebActivator for the call to WebSecurity.InitializeDatabaseConnection(), but I get an error that no default membership provider can be found.
It’s like it doesn’t see the programmatically registered SimpleMembershipProvider until after the WebActivator.PreApplicationStartMethod. Hence, the reason for having to put the call in Global.asax.cs.
If you know of a way where I can do the database initialization inside of my WebActivator and have it find the default membership provider, I’d love to know how as I’d prefer to do it that way too so that I don’t “muddy” up the project.
Thanks,
Adam
about 2 years ago
I may be missing something, but the MVC (3 RTM) AccountController.Register() method calls MembershipService.CreateUser (model.UserName, model.Password, model.Email) but in WebMatrix.WebData.SimpleMembershipProvider::CreateUser(…) it throws a NotSupportException if InitializeCalled is true (verified with Reflector).
Maybe it should be calling SimpleMembershipProvider.CreateUserAndAccount(…) instead? The problem with this is that CreateUserAndAccount is not defined in the MembershipProvider base class, so it can’t be called using the AccountController._provider member variable. So, I modified AccountController.Register() to include a check for SimpleMembershipProvider as follows, and it works!
public MembershipCreateStatus CreateUser (string userName, string password, string email) { if (String.IsNullOrEmpty (userName)) throw new ArgumentException ("Value cannot be null or empty.", "userName"); if (String.IsNullOrEmpty (password)) throw new ArgumentException ("Value cannot be null or empty.", "password"); if (String.IsNullOrEmpty (email)) throw new ArgumentException ("Value cannot be null or empty.", "email"); MembershipCreateStatus status; var smp = _provider as SimpleMembershipProvider; if (smp != null) { try { smp.CreateUserAndAccount (email, password, true); status = MembershipCreateStatus.Success; } catch (Exception ex) { status = MembershipCreateStatus.ProviderError; } } else _provider.CreateUser (userName, password, email, null, null, true, null, out status); return status; }Am I working too hard here? Let me know if there’s a better/easier way, thanks!
about 2 years ago
@Philip
To answer your question, it depends.
Just to be clear, Microsoft has stated (see the comments) that SimpleMembership is not really “supported” with MVC3. As you’ve seen with the MembershipService.CreateUser issue in your example, the SimpleMembershipProvider does not have the same signature as other ASP.NET membership providers, so it isn’t plug-in-play compatible with existing membership provider code.
So, you have a couple of options if you want to use SimpleMembership with MVC3:
OR
It’s really a matter of where you are coming from. If you are starting fresh, I’d say use the included WebSecurityService.cs in the package. If you’re trying to switch an existing MVC site to use SimpleMembership, then your approach could help reduce the amount of change needed to take advantage of SimpleMembership. Although, it won’t be as clean as using the included WebSecurityService.cs.
Hope that helps!
about 2 years ago
OK, so by “Use the WebSecurityService included” do you mean use IWebSecurityService/WebSecurityService in place of IMembershipService/MembershipService in the MVC app’s AccountController?
about 2 years ago
@Philip
Yes.
Since SimpleMembership doesn’t match the existing .NET membership APIs, you can’t really use the default IMembershipService. That’s why I created IWebSecurityService/WebSecurityService so that you could use this as a replacement for IMembershipService/MembershipService.
about 2 years ago
I wanted to try and use your nuget package in an MVC application that uses the SimpleMembership generated SQL tables to control membership and roles but authentication is Windows. Any ideas who I would go about this?
about 2 years ago
I created a MVC3 app, used NuGet to add SimpleMembership, DotNetOpenAuth & EF4.1. Have not done much of anything else yet and am getting this (very weird) error:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name ‘Data’ does not exist in the namespace ‘WebMatrix’ (are you missing an assembly reference?)
Source Error:
Line 25: using System.Web.Mvc.Html;
Line 26: using System.Web.Routing;
Line 27: using WebMatrix.Data;
Line 28: using WebMatrix.WebData;
Line 29:
Source File: c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\8c98fee1\5862d062\App_Web_index.cshtml.a8d08dba.kbpcxtda.0.cs Line: 27
about 2 years ago
Grabbed this from NuGet, looks promising, but I’m running into an issue from the start and must be missing something. On a valid connection string, I’m getting: System.ArgumentException: Keyword not supported: ‘initial catalog’.
I’m wanting/allowing EF to generate the db via an initialization strategy, so I thought perhaps that it was throwing the error due to the database not being created yet (race condition?), but when I disable simple membership via setting the appSettings flag to false, I then get the following: The Role Manager feature has not been enabled.
Maybe I’m missing something in the process of setting this up, but the docs for doing so are pretty minimal. Any ideas what I’m doing wrong?
about 2 years ago
Found a bug in your implementation of WebSecurityService.cs line 20.
The implementation of CreateUserAndAccount doesn’t pass the value of requireConfirmationToken along to the call to WebSecurity.CreateUserAndAccount.
about 2 years ago
@Keith,
Sorry for the delay in my response.
Not sure why it’s complaining about a dependency on WebMatrix.Data. However, if you add the following line to your web.config (under system.web/compilation/assemblies) it should fix the problem:
I’ll look at adding this to the web.config.transform for the NuGet package.
Thanks for reporting this issue.
Adam
about 2 years ago
Thanks Phil!
Just fixed this and published to NuGet.
about 2 years ago
@Nick,
I think I’ve seen this before. Can you post your sample connection string and I’ll take a look?
Thanks,
Adam
about 1 year ago
Do you guys have a link with a sample of this so I know that it actually works?
about 1 year ago
I want to use SimpleMembership in an MVC 3 website, but I’m getting the following error:
System.ArgumentException was unhandled by user code. Unable to find the requested .Net Framework Data Provider. It may not be installed.
I’m using a SQL Server database, through Entity Framework. Here is my connection string:
I already use EF in other parts of the application, so this connection string is correct and I have connection to the database. Can you please help?
about 1 year ago
For some reason I can’t get it to work. Here is the string
( WebSecurity.InitializeDatabaseConnection(connectionStringName: “data source=SERVER;Initial Catalog=DEFENDANT;Persist Security Info=True;User ID=id;Password=password;Connection Timeout=9000″, userTableName: “Users”, userIdColumn: “ID”, userNameColumn: “Username”, autoCreateTables: true);
That same string is working on web.conf file.
I try doing it with the websercurityService, but I don’t know how or where to register the IWebSercurityService.
Thanks,
Benito
about 1 year ago
@Jon,
I’ve posted a step-by-step walk-through on how to get this working with an MVC3 app. Sample code is included.
Let me know if you have any questions.
Adam
about 1 year ago
@Benito,
connectionStringName should be the actual name of the connection string in your Web.config file, not the connection string itself. Take a look at my most recent post which includes a sample project. That might clear things up.
Adam
about 1 year ago
@Bernardo,
Take a look at my most recent post which includes a sample project from the walk-through. That might help clear things up.
Let me know if you have any questions.
Adam
about 1 year ago
I have a question, if I wanna get other people’s password, all I need to do is input them username and my email address, then I can reset a new password for that account. Right?
I asked this, because I noticed that no email has been saved into database.
about 1 year ago
@Eric,
You’re right the current ForgotPassword page would allow you to get another user’s password. Really, this is just stubbed out to allow you to use one or the other. I typically use email address as the username (in which case, I remove the username field.) If you actually have a username and separate email address field, then you’ll need to implement some kind of GetUserNameByEmail(string emailAddress) method that will query the db and lookup the username which SimpleMembership requires for password reset.
I know this has caused some confusion and I’m planning on updating the Sample package to simply have email address on the ForgotPassword page. If you use email address as username, then no change would be required. But if you have email address in addition to username, then you would need to do the custom lookup since the WebSecurity api doesn’t provide a native way to reset a password by email address (since it doesn’t know what field that would actually be in the db).
Hope that makes sense.
Adam
about 1 year ago
When I try register a user I get this exception….
System.NotSupportedException was unhandled by user code
Message=Specified method is not supported.
Source=WebMatrix.WebData
StackTrace:
at WebMatrix.WebData.SimpleMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status)
at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status)
at Test4.Controllers.AccountController.Register(RegisterModel model) in C:\ASPDOTNET\Test4\Test4\Controllers\AccountController.cs:line 82
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClass15.b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
Here’s the connection string…
Thanks
Mike
about 1 year ago
@Mike,
Looks like the connection string didn’t come across. Are you using Entity Framework? You may have to modify the connection string slightly to get it to work with WebSecurity.
Let me know.
Adam
about 1 year ago
Hi,
When this is executed:
public string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)
{
return WebSecurity.CreateUserAndAccount(userName, password, propertyValues, requireConfirmationToken);
}
I get the following error:
To call this method, the “Membership.Provider” property must be an instance of “ExtendedMembershipProvider”.
I am guessing this is down to the fact that I am using SQLCE4.0 and therefore had to replace all SQL providers in web.config with the universal ones. This means I replaced AspNetSqlMembershipProvider with DefaultMembershipProvider. Ever since, my simpleMembership stopped working (and I do have the “enableSimpleMembership” value=”true” in appSettings).
Any ideas? I am stuck big time here.
Thanks in advance,
Polis
about 1 year ago
Ok, got it.
Changed my existing provider to:
and it worked.
Now moving onto another problem I could use some help
When trying to register with a user whose email address belongs to another user in the db, this:
public string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)
{
return WebSecurity.CreateUserAndAccount(userName, password, propertyValues, requireConfirmationToken);
}
throws an unhandled MembershipCreateUserException with the message “username already exists”. The code that triggers this (from my accountController) is:
MembershipCreateStatus createStatus;
createStatus = MembershipCreateStatus.Success;
var requireEmailConfirmation = true;
var token = WebSecurityService.CreateUserAndAccount(model.UserName, model.Password, requireEmailConfirmation);
There is a call to ModelState.AddModelError(“”,ErrorCodeToString(createStatus)); but this is further down the execution.
How can I handle this exception? Any ideas?
Thanks again,
Polis.
about 7 months ago
I’m using SimpleMembership.MC3 without problems in development, but when I deploy to azure I get the following error:
Could not load file or assembly ‘WebMatrix.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies.
This assembly is not included in the Nuget Package. What should I do? Thank you.
about 7 months ago
@Seb,
WebMatrix.Data should be included in the NuGet package. Can you check your bin directory?
Easiest solution should be to xcopy that to Azure in your bin folder.