25

I can't make WebSecurity object work anywhere except what's already been generated in AccountController.cs file. Account controller has [InitializeSimpleMembership] attribute set at the top. Login functions don't complain about calling WebSecurity.Login(...), for example. I added a child action to AccountController:

[ChildActionOnly]
        [AllowAnonymous]
        public ActionResult NavBar()
        {
            NavBarViewModel viewModel = new NavBarViewModel();
            viewModel.LinkItems = new List<NavBarLinkItem>();

            if (Request.IsAuthenticated)
            {
                SimpleRoleProvider roleProvider = new SimpleRoleProvider();
                if (roleProvider.IsUserInRole(User.Identity.Name, "User"))
                {
                    viewModel.LinkItems.Add(new NavBarLinkItem() 
                    { Title = "Create Project", Action = "Create", Controller = "Project" });

                }

            }

            viewModel.LinkItems.Add(new NavBarLinkItem() { Title="Help", Action="Index", Controller="Help" });

            return PartialView("_NavBar", viewModel);
        }

Left as is, the code crashes on "if (roleProvider.IsUserInRole(User.Identity.Name, "User"))" line with the subject error message. So I go into InitialzeSimpleMembershipAttribute.cs file and copy/paste this line at the top of my function:

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

... and get an error message that WebSecurity.InitializeDatabaseConnection should only be called once. This makes sense, because there is an attribute at the top of the controller definition that should've called this function already (and it seems it does that just fine). So to be safe, I change above call to:

if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId",
                                                         "UserName", autoCreateTables: true);
            }

... and get back the original error message, that WebSecurity.InitializeDatabaseConnection should be called before blah blah blah. Any insight into this madness would be greatly appreciated

5 Answers 5

49

There's a better explanation here: http://odetocode.com/blogs/scott/archive/2012/09/24/perils-of-the-mvc4-accountcontroller.aspx

Here's all you have to do:

  1. Remove [InitializeSimpleMembership] from the top of AccountController
  2. Copy the WebSecurity.InitializeDatabaseConnection(...) call from /Filters/InitializeSimpleMembershipAttribute.cs (line 39) to /AppStart/AuthConfig.cs
  3. Feel free to remove InitializeSimpleMembershipAttribute.cs from your project

You don't have to add the InitializeDatabaseConnection() call to AuthConfig.RegisterAuth() but it seems like the logical place and keeps your Global.asax cleaner.

What you are essentially doing is extracting the initialization call from the original attribute and explicitly calling it on Application_Start. Everything else in the attribute is just conditional checking in case you aren't using (or don't need) SimpleMembership.

2
  • I was able to just put the [InitializeSimpleMembership] attribute at the top of my controller, and it works now.
    – jwatts1980
    Commented Feb 2, 2014 at 20:59
  • What are the ramifications of doing this though? I imagine it is like this for a reason.
    – Paul C
    Commented Oct 31, 2014 at 14:07
9

Adding the [InitializeSimpleMembership] (as mentioned and found in the AccountController) to the top of the controller I needed to access WebSecurity from did the trick for me. Not sure however if its the intended implementation method though...

[InitializeSimpleMembership]
public class DataController : Controller
{ ... }
5

I found this on the interwebs: http://forums.asp.net/t/1718361.aspx/1 Basically, don't use SimpleRoleProvider type. There is a Roles object available that allows simple calls like this:

if (Request.IsAuthenticated)
{
  if( Roles.IsUserInRole(User.Identity.Name, "User"))
  {
    viewModel.LinkItems.Add(new NavBarLinkItem() 
    { Title = "Create Project", Action = "Create", Controller = "Campaign" });
  }
}
1
  • 1
    This really isn't as clear as perhaps it needs to be. I looked at the link, but it's not relevant to what I'm doing (I think?) as I'm not trying to create a Role. I have the same problem you did, I get a "can't call this twice" message, but when I take the "second" one out, I get the "you must call..." message. What is crashing with the "you must call..." message is: if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)) Any ideas? Commented Dec 26, 2012 at 2:44
1

First you have to set your role and membership provider in the web.config:

<authentication mode="Forms">
  <forms loginUrl="/Account/Login" slidingExpiration="true" timeout="60" />
</authentication>
<membership defaultProvider="p1">
  <providers>
    <add name="p1" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="p1">
  <providers>
    <add name="p1" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
  </providers>
</roleManager>

When you create a new instance of SimpleRoleProvider, use the non-null constructor, and supply the default RoleProvider set in the web.config as an argument:

SimpleRoleProvider srp = new SimpleRoleProvider(Roles.Provider);

The solution is the same in the case of SimpleMembershipProvider:

SimpleMembershipProvider msp = new SimpleMembershipProvider(Membership.Provider);
1

In my case I had to disable Anonymous Authentication within the IIS Authentication setting.

Then I had to enable Forms and Windows Authentication. This will of course depend on whichever authentication you require for your app.

Once I did that the error went away and the app worked as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.