Note that there are some explanatory texts on larger screens.

plurals
  1. POasp.net 4.5 custom membership provider configuration throws strange exception
    text
    copied!<p>My web site was initially written in MVC 4.0 RC using VS2010, . I have just downloaded and installed VS2012, and upgraded my project to Dotnet Framework 4.5.</p> <p>In my project I'm using a Custom MemberShipProvider and a custom RoleProvider. On VS2010 it worked like a charm. But now I'm keeping getting a strange Configuration Error:</p> <p>"This method cannot be called during the application's pre-start initialization phase."</p> <p>The "system.web -> membership -> providers -> add" line in my web.config is marked red as the source of the problem.</p> <p>I eliminated the suspicion that the problem has something to do with the migration process, by creating a new MVC 4.0 Project (in VS2012), adding my custom Membership/Role providers, changing the web.config appropriately, and finding that the error reappears!</p> <p>Digging deeper into the problem - I found the following information in the Application Log:</p> <blockquote> <p>Exception information: Exception type: InvalidOperationException Exception message: The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception with the following error message: This method cannot be called during the application's pre-start initialization phase. (C:\Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config line 52).<br> at System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection<code>1 methods, Func</code>1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) at System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) at System.Web.Compilation.BuildManager.ExecutePreAppStart() at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)</p> <p>This method cannot be called during the application's pre-start initialization phase. (C:\Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config line 52)<br> at System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement, XmlNode node, Boolean checkAptcaBit, Boolean ignoreCase) at System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement, Boolean checkAptcaBit, Boolean ignoreCase) at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType) at System.Web.Configuration.ProvidersHelper.InstantiateProviders(ProviderSettingsCollection configProviders, ProviderCollection providers, Type providerType)<br> at System.Web.Security.Membership.InitializeSettings(Boolean initializeGeneralSettings, RuntimeConfig appConfig, MembershipSection settings) at System.Web.Security.Membership.Initialize() at System.Web.Security.Membership.get_Providers() at WebMatrix.WebData.WebSecurity.PreAppStartInit() at WebMatrix.WebData.PreApplicationStartCode.Start()</p> <p>This method cannot be called during the application's pre-start initialization phase. at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()<br> at System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) at System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement, XmlNode node, Boolean checkAptcaBit, Boolean ignoreCase)</p> <pre><code>Request information: Request URL: http://localhost:4995/ Request path: / User host address: ::1 User: Is authenticated: False Authentication Type: Thread account name: AD\dov Thread information: Thread ID: 5 Thread account name: AD\dov Is impersonating: False Stack trace: at &gt;System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 </code></pre> <p>methods, Func<code>1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection</code>1 methods) at System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) at System.Web.Compilation.BuildManager.ExecutePreAppStart() at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)</p> </blockquote> <p>Please help,</p> <p>Thank you!</p> <p>Here is the web.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt; &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt; &lt;/configSections&gt; &lt;connectionStrings&gt; &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MyWebSite-20120820105950;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MyWebSite-20120820105950.mdf" providerName="System.Data.SqlClient" /&gt; &lt;add name="MyWebSiteDbContext" providerName="System.Data.SqlClient" connectionString="server=.;database=MyWebSiteDB;Integrated Security=True;" /&gt; &lt;/connectionStrings&gt; &lt;appSettings&gt; &lt;add key="webpages:Version" value="2.0.0.0" /&gt; &lt;add key="webpages:Enabled" value="false" /&gt; &lt;add key="PreserveLoginUrl" value="true" /&gt; &lt;add key="ClientValidationEnabled" value="true" /&gt; &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; &lt;/appSettings&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5" /&gt; &lt;httpRuntime targetFramework="4.5" /&gt; &lt;authentication mode="Forms"&gt; &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt; &lt;/authentication&gt; &lt;pages&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Helpers" /&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Optimization" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="System.Web.WebPages" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;profile&gt; &lt;providers&gt; &lt;clear/&gt; &lt;/providers&gt; &lt;/profile&gt; &lt;roleManager defaultProvider="MyWebSiteRoleProvider" enabled="true"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="MyWebSiteRoleProvider" type="MyWebSite.Security.MyWebSiteRoleProvider"/&gt; &lt;/providers&gt; &lt;/roleManager&gt; &lt;membership defaultProvider="MyWebSiteMembershipProvider"&gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="MyWebSiteMembershipProvider" type="MyWebSite.Security.MyWebSiteMembershipProvider" /&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false" /&gt; &lt;handlers&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="v11.0" /&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;/entityFramework&gt; &lt;/configuration&gt; </code></pre> <p>This is the relevant custom membership (I have simplified it, but even though the problem is still there) code, only ValidateUser is really overridden:</p> <pre><code>using System; using System.Linq; using System.Web.Security; using DAL.MyWebSite; namespace MyWebSite.Security { public class MyWebSiteMembershipProvider : MembershipProvider { /// &lt;summary&gt; /// Verifies that the specified user name and password exist in the data source. /// &lt;/summary&gt; /// &lt;returns&gt; /// true if the specified username and password are valid; otherwise, false. /// &lt;/returns&gt; /// &lt;param name="username"&gt;The name of the user to validate. &lt;/param&gt;&lt;param name="password"&gt;The password for the specified user. &lt;/param&gt; public override bool ValidateUser(string username, string password) { // simplified return true; } } } </code></pre> <p>This is the (simplified) RoleProvider:</p> <pre><code>using System; using System.Linq; using System.Web.Security; using DAL.MyWebSite; namespace MyWebSite.Security { public class MyWebSiteRoleProvider : RoleProvider { //readonly MyWebSiteDbContext _context = new MyWebSiteDbContext(); /// &lt;summary&gt; /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName. /// &lt;/summary&gt; /// &lt;returns&gt; /// true if the specified user is in the specified role for the configured applicationName; otherwise, false. /// &lt;/returns&gt; /// &lt;param name="username"&gt;The user name to search for.&lt;/param&gt;&lt;param name="roleName"&gt;The role to search in.&lt;/param&gt; public override bool IsUserInRole(string username, string roleName) { return true; //return GetRolesForUser(username).Contains(roleName); } /// &lt;summary&gt; /// Gets a list of the roles that a specified user is in for the configured applicationName. /// &lt;/summary&gt; /// &lt;returns&gt; /// A string array containing the names of all the roles that the specified user is in for the configured applicationName. /// &lt;/returns&gt; /// &lt;param name="username"&gt;The user to return a list of roles for.&lt;/param&gt; public override string[] GetRolesForUser(string username) { return new string[] {"one", "two"}; //var sm = _context.SalesManagers.Include("PermissionLevel").FirstOrDefault(manager =&gt; manager.UserName == username); //if (sm != null) //{ // if (sm.PermissionLevel.Name == "Sales Manager") // { // return new[] { "SalesManagers" }; // } // if (sm.PermissionLevel.Name == "Administrator") // { // return new[] { "SalesManagers", "Administrators" }; // } //} //return null; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload