ASP.NET MVC 4, "WebSecurity.InitializeDatabaseConnection"方法只能调用一次

标签 asp.net asp.net-mvc asp.net-mvc-4 simplemembership

我正在 Visual Studio 2012 Express 中开发代码优先的 Web 应用程序。

我在 web.config 中使用这个连接字符串:

<add name="myContext" connectionString="Data Source=.;Integrated Security=True;Initial Catalog=cityKingMVC4" providerName="System.Data.SqlClient" />

我正在使用 SimpleMembership。

我正在尝试从 Filters/InitializeSimpleMembershipAttribute.cs 为 1 个管理员提供种子:
...
WebSecurity.InitializeDatabaseConnection("myContext", "Users", "UserId", "Email", autoCreateTables: true);

// A: Create Admin user
if (!WebSecurity.ConfirmAccount("admin@mydom.com"))
{
   WebSecurity.CreateUserAndAccount("admin@mydom.com", "password");
}

// B: Create admin role if not exist
if (!Roles.RoleExists("Administrator"))
{
   Roles.CreateRole("Administrator");
   Roles.AddUserToRole("admin@mydom.com", "Administrator");
}

如果我评论 A & B 它不会崩溃。如果我不这样做,我会得到这个:
“WebSecurity.InitializeDatabaseConnection”方法只能调用一次。

如果我调试并在 'WebSecurity.InitializeDatabaseConnection' 上放置一个断点 - 它只调用一次,并且没有其他代码在任何地方调用 WebSecurity.InitializeDatabaseConnection。

如果我调试 - 它会在文件(标准 SimpleAuthentication 文件)中更高的另一行上崩溃:
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);

出现此错误:
调用的目标已抛出异常。

堆栈跟踪:
[InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.]
   WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +87978
   WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +86
   myapPMVC4.Filters.SimpleMembershipInitializer..ctor() in c:\Users\name\Documents\Visual Studio 2012\Projects\myapPMVC4\myapPMVC4\Filters\InitializeSimpleMembershipAttribute.cs:43

[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
   myapPMVC4.Filters.SimpleMembershipInitializer..ctor() in c:\Users\name\Documents\Visual Studio 2012\Projects\myapPMVC4\myapPMVC4\Filters\InitializeSimpleMembershipAttribute.cs:88

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +256
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +127
   System.Activator.CreateInstance(Type type) +11
   System.Threading.LazyHelpers`1.ActivatorFactorySelector() +72
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +241
   System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +139
   myapPMVC4.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Users\name\Documents\Visual Studio 2012\Projects\myapPMVC4\myapPMVC4\Filters\InitializeSimpleMembershipAttribute.cs:22
   System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +145
   System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +840201
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +266
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +202
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +112
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +839055
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +826145
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +401
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +786250
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +343
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12550291
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

这是怎么回事?

谢谢
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using System.Web.Security;
using myapPMVC4.Models;

namespace myapPMVC4.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
           LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        { 
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    //WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    if (!WebSecurity.Initialized)
                    {
                       WebSecurity.InitializeDatabaseConnection("myapPMVC4DBContext", "Users", "UserId", "Email", autoCreateTables: true);
                    }


                    // Create Admin user
                    if (!WebSecurity.ConfirmAccount("admin@myapp.com"))
                    {
                       //WebSecurity.CreateUserAndAccount("admin", "pass", new { email = "a@b.com" });
                       WebSecurity.CreateUserAndAccount("admin@myapp.com", "pass");
                    }

                    // Create admin role if not exist
                    if (!Roles.RoleExists("Administrator"))
                    {
                       Roles.CreateRole("Administrator");
                       Roles.AddUserToRole("admin@myapp.com", "Administrator");
                    }


                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}

最佳答案

问题 ...
InitializeDatabaseConnection电话WebSecurity.InitializeProviders在内部,这个方法 不是线程安全的 ,然后将此与 WebSecurity 通常需要从不同位置初始化的事实相结合。这会产生影响,因为 Web 应用程序本质上是多线程环境......和 ​​WebSecurity.InitializedWebSecurity.InitializeDatabaseConnection一起使用时不是线程安全的 - 它们会产生典型的竞争条件。
播种(用于迁移)意味着您的 WebSecurity可以多次初始化,因为您可能还需要在 Global.asax.cs 中初始化它以用于关闭种子的部署,并且您的 InitializeSimpleMembershipAttribute在实时部署等中,可能会被 http 请求同时调用多次。
将初始化代码放在多个地方也会破坏您的 DRY内在
解决方案 ...
确保您的 init 调用是线程安全的,并且每个 AppDomain 实例仅发生一次。使用线程安全的单例类来做到这一点;并减少代码重复。
调用单例的EnsureInitialize适合您的应用程序的以下任何/所有方法:

  • Global.asax.cs(Application_Start 方法在其他任何事情之前)
  • 迁移\Configuration.cs Seed方法(在创建用户之前)
  • Filters\InitializeSimpleMembershipAttribute.cs(在上下文初始化后的 SimpleMembershipInitializer 构造函数中)

  • 这是一个简单的单例示例:
    // Call this with WebSecurityInitializer.Instance.EnsureInitialize()
    public class WebSecurityInitializer {
        private WebSecurityInitializer() { }
        public static readonly WebSecurityInitializer Instance = new WebSecurityInitializer();
        private bool isNotInit = true;
        private readonly object SyncRoot = new object();
        public void EnsureInitialize() {
            if (isNotInit) {
                lock (this.SyncRoot) {
                    if (isNotInit) {
                        isNotInit = false;
                        WebSecurity.InitializeDatabaseConnection("MyContextName",
                            userTableName: "UserProfile", userIdColumn: "UserId", userNameColumn: "UserName",
                            autoCreateTables: true);
                    }
                }
            }
        }
    }
    
    一旦我这样做了,你提到的错误案例就消失了,再也看不到了。

    脚注
    单例类还保留您的代码 DRY ,如果您以后需要更改 WebSecurity.InitializeDatabaseConnection 的配置,这在早期应用程序开发期间特别有用。因为它只会在一个地方(结束编辑)
    我也保留了SimpleMembershipInitializer干净,而是将我的用户与 Migrations\Configuration.cs Seed 中的常见种子一起播种方法。通过将所有内容保存在一个地方,这有助于通过我的迁移进行播种的可测试性。我使用单元测试来确保我们始终可以在迁移树中上下移动,因此这可以更容易地做到这一点。
    然而,你的种子代码的位置并不重要,更重要的是确保在全局范围内,你在 AppDomain 中只初始化了一次 WebSecurity,并且对 InitializeDatabaseConnection 的任何调用是线程安全的。

    关于ASP.NET MVC 4, "WebSecurity.InitializeDatabaseConnection"方法只能调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16508934/

    相关文章:

    c# - 我有一个网格 Vied,当我通过 ASP.net 中的网格上传文件时,我想将网格行详细信息插入到新表中

    c# - ASP.net MVC View 是 "class"吗?

    c# - Inproc 和 Outproc session 状态模式

    asp.net - 为 favicon 添加忽略路由后如何修复 "File does not exist"错误

    asp.net-mvc - 将部分 View 渲染为字符串 MVC4

    javascript - AJAX 调用后设置下拉值不起作用

    c++ - 轻松地将 Simplemembership 集成到现有的 Web 应用程序中

    asp.net-mvc - 我可以在具有添加/删除功能的 MVC 4 View 中显示复杂对象的列表吗?

    javascript - 具有 ID 的单个 Div 未通过 Jquery 隐藏在表单标记内

    javascript - 从后面的代码运行 JavaScript 代码到 updatePanel