asp.net 4.5自定义成员资格提供程序配置抛出奇怪的异常

ber*_*762 30 asp.net asp.net-mvc-4 .net-4.5 visual-studio-2012

我的网站最初是使用VS2010在MVC 4.0 RC中编写的.我刚下载并安装了VS2012,并将我的项目升级到了Dotnet Framework 4.5.

在我的项目中,我使用Custom MemberShipProvider和自定义RoleProvider.在VS2010上,它就像一个魅力.但现在我一直在收到一个奇怪的配置错误:

"在应用程序的预启动初始化阶段,无法调用此方法."

我的web.config中的"system.web - > membership - > providers - > add"行被标记为红色作为问题的根源.

通过创建一个新的MVC 4.0项目(在VS2012中),添加我的自定义成员资格/角色提供程序,适当地更改web.config以及发现错误再次出现,我消除了对该问题与迁移过程有关的怀疑!

深入研究问题 - 我在应用程序日志中找到了以下信息:

异常信息:异常类型:InvalidOperationException异常消息:预应用程序启动初始化方法启动类型WebMatrix.WebData.PreApplicationStartCode引发异常,并显示以下错误消息:在应用程序的启动前初始化阶段无法调用此方法.(C:\ Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config第52行).
System.Web处理1 methods, FuncSystem.Web.Compilation.BuildManager.CallPartInitMethods(String preStartInitListPath)的System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1方法)中的System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection 1 setHostingEnvironmentCultures). System.Web.Hosting.HostingEnvironment.Initialize中的Compilation.BuildManager.ExecutePreAppStart()(ApplicationManager appManager,IApplicationHost appHost,IConfigMapPathFactory configMapPathFactory,HostingEnvironmentParameters hostingParameters,PolicyLevel policyLevel,Exception appDomainCreationException)

在应用程序的预启动初始化阶段期间无法调用此方法.
System.Web.Configuration.ConfigUtil.GetType(String typeName,String propertyName,ConfigurationElement configElement,XmlNode node )中的(C:\ Users\dov.AD\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\web.config第52行),System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings,Type providerType)中的System.Web.Configuration.ConfigUtil.GetType(String typeName,String propertyName,ConfigurationElement configElement,Boolean checkAptcaBit,Boolean ignoreCase)中的布尔checkAptcaBit,Boolean ignoreCase)在System.Web.Security.Meithip.Initialize
上System.Web.Security.Membership.InitializeSettings(Boolean initializeGeneralSettings,RuntimeConfig appConfig,MembershipSection设置)的System.Web.Configuration.ProvidersHelper.InstantiateProviders(ProviderSettingsCollection configProviders,ProviderCollection providers,Type providerType)中()WebMatrix.WebData.WebSecurity.PreA上的System.Web.Security.Membership.get_Providers()WebMatrix.WebData.PreApplicationStartCode.Start()上的ppStartInit()

在应用程序的预启动初始化阶段期间无法调用此方法.在System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
在System.Web.Compilation.BuildManager.GetType(字符串的typeName,布尔throwOnError,布尔IGNORECASE)在System.Web.Configuration.ConfigUtil.GetType(字符串的typeName,字符串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
Run Code Online (Sandbox Code Playgroud)

1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollectionSystem.Web.Compos.HalltingEnvironment.Initialize(ApplicationManager appManager,IApplicationHost appHost,IConfigMapPathFactory)上System.Web.Compilation.BuildManager.ExecutePreAppStart()的System.Web.Compilation.BuildManager.CallPreInartMethods(String preStartInitListPath)中的方法,Func 1方法) configMapPathFactory,HostingEnvironmentParameters hostingParameters,PolicyLevel policyLevel,Exception 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>
Run Code Online (Sandbox Code Playgroud)

这是相关的自定义成员(我已经简化了,但即使问题仍然存在)的代码,只有的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;
        }



    }
}
Run Code Online (Sandbox Code Playgroud)

这是(简化的)RoleProvider:

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;

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ius 70

我在自MVC2中使用自己的自定义成员资格和角色提供程序,并在从MVC3迁移到4时遇到此问题.

我在MVC4/.net4.5 EF5中创建了一个新项目,并且遇到了这个错误.

我设法通过执行以下操作来修复它:

将其添加到您的webconfig appsettings:

  <appSettings>
    <add key="enableSimpleMembership" value="false"/>
    <add key="autoFormsAuthentication" value="false"/>
  </appSettings>
Run Code Online (Sandbox Code Playgroud)

如果尚未设置,请将您的连接字符串添加到您的成员资格和角色提供者:

<membership defaultProvider="MyMembershipProvider">
  <providers>
    <add name="MyMembershipProvider" type="AMS.WebUI.Infrastructure.CustomMembershipProvider" connectionStringName="EFDbContext" />
  </providers>
</membership>
<roleManager defaultProvider="MyRoleprovider">
  <providers>
    <add name="MyRoleprovider" type="AMS.WebUI.Infrastructure.CustomRoleProvider" connectionStringName="EFDbContext" />
  </providers>
</roleManager>
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题,我希望它可以帮助你.


Oli*_*Oli 24

好吧,让我们看看我是否可以解释这一点.ASP.NET 4引入了一个新的程序集级属性:PreApplicationStartMethodAttribute通常在Properties/AssemblyInfo.cs文件中使用.

ASP.NET MVC 4标准模板附带了对WebMatrix.WebData程序集的引用.看看它的代码,AssemblyInfo确实有这个:

[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]
Run Code Online (Sandbox Code Playgroud)

所以基本上,在调用App_Start之前,框架将调用WebMatrix.WebData.PreApplicationStartCode.Start()哪个,除其他外,这样做

// Initialize membership provider
WebSecurity.PreAppStartInit();
Run Code Online (Sandbox Code Playgroud)

当然,就像@Ben Pretorius所说,这种方法就是这样开始的

internal static void PreAppStartInit()
{
    // Allow use of <add key="EnableSimpleMembershipKey" value="false" /> to disable registration of membership/role providers as default.
    if (ConfigUtil.SimpleMembershipEnabled)
    {
        ...
Run Code Online (Sandbox Code Playgroud)

所以你有这个"自动"失败的方式/原因.微软没有<add key="EnableSimpleMembershipKey" value="true" />在标准的Web.config中包含这一点真是太糟糕了,以至于"嘿,这就是设置在这里的SimpleProvider的东西".

  • @ berke762呢,不是吗?你为什么不接受它作为答案呢?Oli和Ben Pretorius都提供了有效的答案,我刚试了一下(与自定义提供商有同样的问题). (3认同)

Gas*_*agy 8

我也在玩这个,并查看WebMatrix代码,最后我认为Ben的解决方案似乎是有效的.

(我也尝试使用程序集引用但没有成功.我认为删除你刚刚实现的配置设置相同的引用 - WebMatrix安全性没有正确初始化.但我认为这是一种非常危险的方式.但是我只是在猜这里.)

对我来说有什么用:

<appSettings>
  <add key="enableSimpleMembership" value="false"/>
</appSettings>

<membership defaultProvider="MyMembershipProvider">
  <providers>
    <clear />
    <add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider" />
  </providers>
</membership>
<!-- this role configuration below uses the SimpleRoleProvider, because I just 
     wanted to replace the membership provider. If you need to replace that one 
     too, just use your own class instead. -->
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
  <providers>
    <remove name="AspNetSqlRoleProvider" />
    <add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <!-- note: WebMatrix registers SimpleRoleProvider with name
         'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
  </providers>
</roleManager>
Run Code Online (Sandbox Code Playgroud)

我检查了WebMatrix代码,似乎将'enableSimpleMembership'设置为false是非常无害的.WebMatrix仅使用它来初始化成员资格/角色提供者(可以由上面的配置代替),并且它允许表单身份验证允许替代配置方式(通过应用程序设置) - 如果您有标准表单,这也没有必要验证配置正确(主要是'loginUrl'是这里唯一重要的播放器).

我还试图检查'autoFormsAuthentication'设置的作用 - 但我没有找到任何东西,所以只是跳过它.看起来很好.