我的网站最初是使用 VS2010 用 MVC 4.0 RC 编写的,. 我刚刚下载并安装了VS2012,并将我的项目升级到Dotnet Framework 4.5。
在我的项目中,我使用了自定义 MemberShipProvider 和自定义 RoleProvider。在 VS2010 上,它就像一个魅力。但现在我不断收到一个奇怪的配置错误:
“在应用程序的预启动初始化阶段无法调用此方法。”
我的 web.config 中的“system.web -> members -> providers -> add”行被标记为红色作为问题的根源。
我通过创建一个新的 MVC 4.0 项目(在 VS2012 中)、添加我的自定义成员资格/角色提供程序、适当地更改 web.config 并发现错误再次出现,从而消除了问题与迁移过程有关的怀疑!
深入研究问题 - 我在应用程序日志中发现了以下信息:
异常信息:异常类型:InvalidOperationException 异常消息:WebMatrix.WebData.PreApplicationStartCode 类型的预应用程序启动初始化方法 Start 引发异常,错误消息如下:在应用程序的预启动初始化阶段无法调用此方法。(C:\Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config 第 52 行)。
在 System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection1 methods, Func
1 setHostingEnvironmentCultures) 在 System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 方法) 在 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) 在 System.Web.Compilation.BuildManager.ExecutePreAppStart() 在 System.Web。 Hosting.HostingEnvironment.Initialize(ApplicationManager appManager,IApplicationHost appHost,IConfigMapPathFactory configMapPathFactory,HostingEnvironmentParameters hostingParameters,PolicyLevel policyLevel,异常 appDomainCreationException)在应用程序的预启动初始化阶段不能调用此方法。(C:\Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config 第 52 行)
在 System.Web.Configuration.ConfigUtil.GetType(字符串 typeName,String propertyName,ConfigurationElement configElement,XmlNode 节点,布尔 checkAptcaBit,Boolean ignoreCase)在 System.Web.Configuration.ConfigUtil.GetType(String typeName,String propertyName,ConfigurationElement configElement,Boolean checkAptcaBit, Boolean ignoreCase) 在 System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType) 在 System.Web.Configuration.ProvidersHelper.InstantiateProviders(ProviderSettingsCollection configProviders, ProviderCollection providers, Type providerType)
在 System.Web.Security.Membership.InitializeSettings(Boolean initializeGeneralSettings, RuntimeConfig appConfig, MembershipSection 设置) 在 System.Web.Security.Membership.Initialize() 在 System.Web.Security.Membership.get_Providers() 在 WebMatrix.WebData.WebSecurity .PreAppStartInit() 在 WebMatrix.WebData.PreApplicationStartCode.Start()在应用程序的预启动初始化阶段不能调用此方法。在 System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
在 System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) 在 System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement、XmlNode 节点、布尔值 checkAptcaBit、布尔值 ignoreCase)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 >System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1
方法,Func
1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection
1 方法)在 System.Web.Compilation.BuildManager.ExecutePreAppStart() 在 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) 在 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, 异常 appDomainCreationException)
请帮忙,
谢谢!
这是web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<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" />
<add name="MyWebSiteDbContext" providerName="System.Data.SqlClient" connectionString="server=.;database=MyWebSiteDB;Integrated Security=True;" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile>
<providers>
<clear/>
</providers>
</profile>
<roleManager defaultProvider="MyWebSiteRoleProvider" enabled="true">
<providers>
<clear/>
<add name="MyWebSiteRoleProvider" type="MyWebSite.Security.MyWebSiteRoleProvider"/>
</providers>
</roleManager>
<membership defaultProvider="MyWebSiteMembershipProvider">
<providers>
<clear />
<add name="MyWebSiteMembershipProvider" type="MyWebSite.Security.MyWebSiteMembershipProvider" />
</providers>
</membership>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<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" />
<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" />
<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" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
这是相关的自定义成员资格(我已对其进行了简化,但即使问题仍然存在)代码,只有 ValidateUser 真正被覆盖:
using System;
using System.Linq;
using System.Web.Security;
using DAL.MyWebSite;
namespace MyWebSite.Security
{
public class MyWebSiteMembershipProvider : MembershipProvider
{
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <returns>
/// true if the specified username and password are valid; otherwise, false.
/// </returns>
/// <param name="username">The name of the user to validate. </param><param name="password">The password for the specified user. </param>
public override bool ValidateUser(string username, string password)
{
// simplified
return true;
}
}
}
这是(简化的)角色提供者:
using System;
using System.Linq;
using System.Web.Security;
using DAL.MyWebSite;
namespace MyWebSite.Security
{
public class MyWebSiteRoleProvider : RoleProvider
{
//readonly MyWebSiteDbContext _context = new MyWebSiteDbContext();
/// <summary>
/// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
/// </summary>
/// <returns>
/// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
/// </returns>
/// <param name="username">The user name to search for.</param><param name="roleName">The role to search in.</param>
public override bool IsUserInRole(string username, string roleName)
{
return true;
//return GetRolesForUser(username).Contains(roleName);
}
/// <summary>
/// Gets a list of the roles that a specified user is in for the configured applicationName.
/// </summary>
/// <returns>
/// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
/// </returns>
/// <param name="username">The user to return a list of roles for.</param>
public override string[] GetRolesForUser(string username)
{
return new string[] {"one", "two"};
//var sm = _context.SalesManagers.Include("PermissionLevel").FirstOrDefault(manager => 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;
}
}
}