asp.net 4.5定义成员资格提供配置会抛出异常诡异 [英] asp.net 4.5 custom membership provider configuration throws strange exception

查看:154
本文介绍了asp.net 4.5定义成员资格提供配置会抛出异常诡异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这种方法不能在应用程序的$ P $对 - 启动初始化阶段称为

在System.Web程序 - >会员 - >供应商 - >添加。在我的web.config行标记红色作为问题的根源

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

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


  

异常信息:
      异常类型:InvalidOperationException异常
      异常消息:在pre-应用程序启动的类型WebMatrix.WebData初始化方法开始preApplicationStart code抛出
  与以下错误消息的异常:这种方法不能
  在应用程序的pre-启动初始化阶段调用。
  (C:\\用户\\ dov.AD \\文档\\ Visual Studio中
  2012 \\项目\\ MvcApplication2 \\ MvcApplication2 \\ web.config行52)。结果
  在
  System.Web.Compilation.BuildManager.Invoke preStartInitMethodsCore(ICollection的 1
  方法,Func键
1 setHostingEnvironmentCultures)在
  System.Web.Compilation.BuildManager.Invoke preStartInitMethods(ICollection`1
  方法)在
  System.Web.Compilation.BuildManager.Call preStartInitMethods(字符串
  preStartInitListPath)的
  System.Web.Compilation.BuildManager.Execute preAppStart()在
  System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
  AppManager的,IApplicationHost APPHOST,IConfigMapPathFactory
  configMapPathFactory,HostingEnvironmentParameters hostingParameters,
  PolicyLevel policyLevel,异常appDomainCreationException)


  
  

此方法不能应用程序的pre-启动时调用
  初始化阶段。 (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.InitializeSet​​tings(布尔
  initializeGeneralSettings,RuntimeConfig AppConfig的,MembershipSection
  设置)在System.Web.Security.Membership.Initialize()在
  System.Web.Security.Membership.get_Providers()在
  WebMatrix.WebData.WebSecurity。preAppStartInit()在
  WebMatrix.WebData。preApplicationStart code.Start()


  
  

此方法不能应用程序的pre-启动时调用
  初始化阶段。在
  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)

 请求信息:
请求URL:http://本地主机:4995 /
请求路径:/
用户主机地址::: 1
用户:
通过身份验证:假
身份验证类型:
线程帐户名:AD \\ DOV线程信息:
线程ID:5
线程帐户名:AD \\ DOV
假冒:假
堆栈跟踪:AT> System.Web.Compilation.BuildManager.Invoke preStartInitMethodsCore(ICollection`1


  
  

方法,Func键 1 setHostingEnvironmentCultures)在
  System.Web.Compilation.BuildManager.Invoke preStartInitMethods(ICollection的
1
  方法)在
  System.Web.Compilation.BuildManager.Call preStartInitMethods(字符串
  preStartInitListPath)的
  System.Web.Compilation.BuildManager.Execute preAppStart()在
  System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
  AppManager的,IApplicationHost APPHOST,IConfigMapPathFactory
  configMapPathFactory,HostingEnvironmentParameters hostingParameters,
  PolicyLevel policyLevel,异常appDomainCreationException)


请帮忙,

感谢您!

下面是在web.config:

 <?XML版本=1.0编码=UTF-8&GT?;
<! -
  有关如何配置ASP.NET应用程序的更多信息,请访问:
  http://go.microsoft.com/fwlink/?LinkId=169433
   - >
<结构>
  < configSections>
    <! - 有关Entity Framework的配置的详细信息,请访问http://go.microsoft.com/fwlink/?LinkID=237468 - >
    <节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本5.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/>
  < / configSections>
  <&是connectionStrings GT;
    <添加名称=DefaultConnection的connectionString =数据源=(的LocalDB)\\ V11.0;初始目录= ASPNET-MyWebSite-20120820105950;集成安全性= SSPI; AttachDBFilename = | DataDirectory目录| \\ ASPNET-MyWebSite-20120820105950.mdf的providerName =System.Data.SqlClient的/>
    <添加名称=MyWebSiteDbContext的providerName =System.Data.SqlClient的的connectionString =服务器=;数据库= MyWebSiteDB;集成安全性= TRUE; />
  < /&是connectionStrings GT;
  <&的appSettings GT;
    <添加键=网页:版本值=2.0.0.0/>
    <添加键=网页:启用VALUE =FALSE/>
    <添加关键=preserveLoginUrlVALUE =真/>
    <添加键=ClientValidationEnabledVALUE =真/>
    <添加键=UnobtrusiveJavaScriptEnabledVALUE =真/>
  < /的appSettings>
  <&的System.Web GT;
    <编译调试=真targetFramework =4.5/>
    <的httpRuntime targetFramework =4.5/>
    <身份验证模式=表格>
      <形式loginUrl =〜/帐号/登录超时=2880/>
    < /认证>
    <网页和GT;
      <&命名空间GT;
        <添加命名空间=System.Web.Helpers/>
        <添加命名空间=System.Web.Mvc/>
        <添加命名空间=System.Web.Mvc.Ajax/>
        <添加命名空间=System.Web.Mvc.Html/>
        <添加命名空间=System.Web.Optimization/>
        <添加命名空间=System.Web.Routing/>
        <添加命名空间=System.Web.WebPages/>
      < /命名空间>
    < /页>
    <型材>
      <供应商>
        <清/>
      < /供应商>
    < / profile文件>
    < roleManager defaultProvider =MyWebSiteRoleProvider启用=真>
      <供应商>
        <清/>
        <添加名称=MyWebSiteRoleProviderTYPE =MyWebSite.Security.MyWebSiteRoleProvider/>
      < /供应商>
    < / roleManager>
    <会员defaultProvider =MyWebSiteMembershipProvider>
      <供应商>
        <清/>
        <添加名称=MyWebSiteMembershipProviderTYPE =MyWebSite.Security.MyWebSiteMembershipProvider/>
      < /供应商>
    < /会员>
  < /system.web>
  < system.webServer>
    <验证validateIntegratedModeConfiguration =FALSE/>
    <&处理GT;
      <清除NAME =ExtensionlessUrlHandler-ISAPI-4.0_32bit/>
      <清除NAME =ExtensionlessUrlHandler-ISAPI-4.0_64bit/>
      <清除NAME =ExtensionlessUrlHandler - 集成 - 4.0/>
      <添加名称=ExtensionlessUrlHandler-ISAPI-4.0_32bitPATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS模块=IsapiModulescriptProcessor ​​=%WINDIR%\\ Microsoft.NET \\框架\\ v4.0.30319 \\ ASPNET_ISAPI.DLLpreCondition = classicMode,runtimeVersionv4.0,bitness32responseBufferLimit =0/>
      <添加名称=ExtensionlessUrlHandler-ISAPI-4.0_64bitPATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS模块=IsapiModulescriptProcessor ​​=%WINDIR%\\ Microsoft.NET \\ Framework64 \\ v4.0.30319 \\ ASPNET_ISAPI.DLLpreCondition = classicMode,runtimeVersionv4.0,bitness64responseBufferLimit =0/>
      <添加名称=ExtensionlessUrlHandler - 集成 - 4.0PATH =*。动词=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSTYPE =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
    < /处理器>
  < /system.webServer>
  <&运行GT;
    < assemblyBinding的xmlns =瓮:架构 - 微软COM:asm.v1>
      < dependentAssembly>
        < assemblyIdentity名称=System.Web.Helpers公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-2.0.0.0NEWVERSION =2.0.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名称=System.Web.Mvc公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-4.0.0.0NEWVERSION =4.0.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名称=System.Web.WebPages公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-2.0.0.0NEWVERSION =2.0.0.0/>
      < / dependentAssembly>
    < / assemblyBinding>
  < /运行>
  <&的EntityFramework GT;
    < defaultConnectionFactory TYPE =System.Data.Entity.Infrastructure.LocalDbConnectionFactory,的EntityFramework>
      <&参数GT;
        <参数值=11.0/>
      < /参数>
    < / defaultConnectionFactory>
  < /&的EntityFramework GT;
< /结构>

这是有关自定义成员资格(我已经简化了,但即使问题仍然存在)code,只有的ValidateUser是真正覆盖:

 使用系统;
使用System.Linq的;
使用System.Web.Security;
使用DAL.MyWebSite;命名空间MyWebSite.Security
{
    公共类MyWebSiteMembershipProvider:的MembershipProvider
    {
        ///<总结>
        ///验证指定的用户名和密码在数据源存在。
        ///< /总结>
        ///<退货和GT;
        ///如果指定的用户名和密码是有效的;否则为false。
        ///< /回报>
        ///&所述; PARAM NAME =用户名>本用户的名称来验证。 < /参数>< PARAM NAME =密码>指定用户的密码。 < /参数>
        公众覆盖布尔的ValidateUser(用户名字符串,字符串密码)
        {
            //简化
            返回true;
        }    }
}

这是(简化)RoleProvider:

 使用系统;
使用System.Linq的;
使用System.Web.Security;
使用DAL.MyWebSite;命名空间MyWebSite.Security
{
    公共类MyWebSiteRoleProvider:RoleProvider
    {
        //只读MyWebSiteDbContext _context =新MyWebSiteDbContext();
        ///<总结>
        ///获取指示指定用户是否属于已配置的a​​pplicationName的指定角色的值。
        ///< /总结>
        ///<退货和GT;
        ///如果指定的用户在已配置的a​​pplicationName的指定角色;否则为false。
        ///< /回报>
        ///&所述; PARAM NAME =用户名>将用户名来搜索与所述; /参数>&下; PARAM NAME =角色名>将作用在搜索和下; /参数>
        公众覆盖布尔的isUserInRole(用户名字符串,字符串角色名)
        {
            返回true;
            //返回GetRolesForUser(用户名)。载有(角色名);
        }        ///<总结>
        ///获取指定用户是已配置的a​​pplicationName的角色的列表。
        ///< /总结>
        ///<退货和GT;
        ///包含所有角色的名称指定用户在配置的applicationName的字符串数组。
        ///< /回报>
        ///&所述; PARAM NAME =用户名>将用户返回角色的列表为&所述; /参数>
        公共重写字符串[] GetRolesForUser(用户名字符串)
        {
            返回新的字符串[] {一,二};            //变种SM = _context.SalesManagers.Include(PermissionLevel)FirstOrDefault(经理= GT; manager.UserName ==用户名)。            //如果(SM!= NULL)
            // {
            //如果(sm.PermissionLevel.Name ==销售经理)
            // {
            //返回新的[] {SalesManagers};
            //}            //如果(sm.PermissionLevel.Name ==管理员)
            // {
            //返回新的[] {SalesManagers,管理员};
            //}            //}
            //返回null;        }    }
}


解决方案

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

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

我设法做修复它以下内容:

添加到您的webconfig的AppSettings:

 <&的appSettings GT;
    <添加键=enableSimpleMembershipVALUE =FALSE/>
    <添加键=autoFormsAuthenticationVALUE =FALSE/>
  < /的appSettings>

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

 <会员defaultProvider =MyMembershipProvider>
  <供应商>
    <添加名称=MyMembershipProviderTYPE =AMS.WebUI.Infrastructure.CustomMembershipProvider的connectionStringName =EFDbContext/>
  < /供应商>
< /会员>
< roleManager defaultProvider =MyRoleprovider>
  <供应商>
    <添加名称=MyRoleproviderTYPE =AMS.WebUI.Infrastructure.CustomRoleProvider的connectionStringName =EFDbContext/>
  < /供应商>
< / roleManager>

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

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.

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:

"This method cannot be called during the application's pre-start initialization phase."

The "system.web -> membership -> providers -> add" line in my web.config is marked red as the source of the problem.

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!

Digging deeper into the problem - I found the following information in the Application Log:

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).
at System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection1 methods, Func1 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)

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

This method cannot be called during the application's pre-start initialization phase. at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
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)

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

methods, Func1 setHostingEnvironmentCultures) at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection1 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)

Please help,

Thank you!

Here is the 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>

This is the relevant custom membership (I have simplified it, but even though the problem is still there) code, only ValidateUser is really overridden:

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



    }
}

This is the (simplified) 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;

        }

    }
}

解决方案

I use my own custom Membership and Role providers in Since MVC2 and ran into this issue when I migrated from MVC3 to 4.

I created a new project in MVC4 / .net4.5 EF5 and had the miss-fortune to encounter this error.

I managed to fix it by doing the following:

Add this to your webconfig appsettings:

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

Add your connection string to your memberships and roles providers if not already set:

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

This resolved the issue for me and I hope it can help you.

这篇关于asp.net 4.5定义成员资格提供配置会抛出异常诡异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆