asp.net 4.5定义成员资格提供配置会抛出异常奇特[复制](asp.net 4.5 custo

2019-06-27 04:52发布

这个问题已经在这里有一个答案:

  • ASP.NET:此方法不能在应用程序的预启动初始化阶段被称为 5回答

我的网站最初是写在MVC 4.0 RC使用VS2010。 我刚才下载并安装VS2012,并升级我的项目DOTNET框架4.5。

在我的项目,我使用自定义的MembershipProvider和一个自定义RoleProvider。 在VS2010它的工作就像一个魅力。 但现在我保持的一个奇怪的配置错误:

“这种方法不能在应用程序的预启动初始化阶段被称为”。

该“的System.Web - >会员 - >供应商 - >添加”线在我的web.config被标记为红色作为问题的根源。

我消除了怀疑,这个问题有事情做与迁移过程中,通过创建一个新的MVC 4.0项目(在VS2012),加入我的自定义会员/角色提供者,适当地改变web.config中,并发现错误再次出现!

挖掘更深的问题 - 我发现,在应用程序日志中的以下信息:

异常信息:异常类型:InvalidOperationException异常消息:在类型WebMatrix.WebData.PreApplicationStartCode预申请启动初始化方法开始抛出异常,并出现以下错误信息:此方法不能在应用程序的预启动初始化阶段被调用。 (C:\用户\ dov.AD \文件\的Visual Studio 2012 \项目\ MvcApplication2 \ MvcApplication2 \ web.config行52)。
在System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection的1 methods, Func 1个setHostingEnvironmentCultures)在System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1方法)在System.Web.Compilation.BuildManager.CallPreStartInitMethods(字符串preStartInitListPath)在System.Web.Compilation.BuildManager.ExecutePreAppStart()在System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager AppManager的,IApplicationHost APPHOST,IConfigMapPathFactory configMapPathFactory,HostingEnvironmentParameters hostingParameters,policyLevel policyLevel,异常appDomainCreationException)

这种方法不能在应用程序的预启动初始化阶段被调用。 (C:\用户\ dov.AD \文件\的Visual Studio 2012 \项目\ MvcApplication2 \ MvcApplication2 \ web.config中管线52)
在System.Web.Configuration.ConfigUtil.GetType(字符串的typeName,字符串propertyName的,的ConfigurationElement configElement,XmlNode的节点,布尔checkAptcaBit,布尔IGNORECASE)在System.Web.Configuration.ConfigUtil.GetType(字符串的typeName,字符串propertyName的,的ConfigurationElement configElement,布尔checkAptcaBit,布尔IGNORECASE)在System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings,类型providerType)在System.Web.Configuration.ProvidersHelper.InstantiateProviders(ProviderSettingsCollection configProviders,ProviderCollection商,类型providerType)
在在System.Web.Security.Membership.get_Providers System.Web.Security.Membership.InitializeSettings(布尔initializeGeneralSettings,RuntimeConfig的AppConfig,MembershipSection设置)在System.Web.Security.Membership.Initialize()()在WebMatrix.WebData.WebSecurity .PreAppStartInit()在WebMatrix.WebData.PreApplicationStartCode.Start()

这种方法不能在应用程序的预启动初始化阶段被调用。 在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 

方法,函数功能1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection在在系统System.Web.Compilation.BuildManager.CallPreStartInitMethods(字符串preStartInitListPath)在System.Web.Compilation.BuildManager.ExecutePreAppStart()1方法)。 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;
        }



    }
}

这是(简化的)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;

        }

    }
}

Answer 1:

我用我自己的自定义成员资格和角色提供者由于MVC2跑进这个问题,当我从MVC3迁移到4。

我在MVC4 / .net4.5 EF5创建了一个新项目,并有小姐,幸运地遇到这个错误。

我设法通过执行以下操作来解决这个问题:

添加到您的webconfig的AppSettings:

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

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

<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>

这解决了这个问题对我来说,我希望它可以帮助你。



Answer 2:

好吧,让我们来看看,如果我能解释这一权利。 ASP.NET 4引入了新的集级属性: PreApplicationStartMethodAttribute ,是通常在所使用的Properties/AssemblyInfo.cs文件。

ASP.NET MVC 4标准模板自带的参考WebMatrix.WebData组装。 看着它的代码 ,该程序集信息确实有这样的:

[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]

所以基本上,甚至调用App_Start之前,该框架将调用WebMatrix.WebData.PreApplicationStartCode.Start()除其他事情,这是否

// Initialize membership provider
WebSecurity.PreAppStartInit();

果然,像@Ben李凌说,该方法开始喜欢这个

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

所以你有怎样/为什么这个“自动”失败。 这真是太糟糕了,微软并没有包括<add key="EnableSimpleMembershipKey" value="true" />标准Web.config文件,使之更加明显,“嘿,有这种SimpleProvider东西,是设置在这里。”



Answer 3:

我也玩弄这一点,展望WebMatrix的代码,最后我认为,本公司的解决方案似乎是一个工作。

(我自己也尝试没有成功与集引用发挥我觉得跟去除引用您刚刚达到相同的配置设置不 - 。在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>

我检查了WebMatrix的代码,它似乎是设置“enableSimpleMembership”为假是相当无害。 WebMatrix中只使用它来初始化成员/角色提供(即可以通过上述的配置被取代)和它使表单认证允许可替换的配置方式(通过应用设置) - 这也不是必需的,如果你有标准形式验证正确配置(主要是“loginUrl”是唯一重要的球员在这里)。

我也曾尝试检查“autoFormsAuthentication”设置做什么 - 但我没有发现任何东西,所以就跳过它。 看起来很好动。



Answer 4:

我已经解决了这个问题。 我发现,当您创建VS2012 MVC 4项目,模板增加了引用一些组件,其中:WebMatrix中和OAuth ......我只是删除这些引用,问题就消失了。 我不知道怎么回答这个问题解决了,但我看到的是,异常来自WebMatrix的大会,所以对于这个原因,我试图将其删除。 很抱歉,但我没有时间投资在调查....



文章来源: asp.net 4.5 custom membership provider configuration throws strange exception [duplicate]