WebSecurity.InitializeDatabaseConnection方法只能被调用一次。

12

我正在尝试使用Windows Azure来托管一个MVC4 Web应用程序。 我使用VS2012 MVC4互联网应用程序模板创建了一个测试应用程序,并向其中添加了自定义的Model和Controller。

我已经将它发布到Azure,并成功地将“update-database”应用到Azure数据库中。

当我在本地尝试使用Azure SQL数据库运行该应用程序时,它运行良好。我可以登录/注册并使用我的测试Controller。

但是当我在线尝试运行该应用程序时,虽然可以使用测试Controller,但登录或注册链接会给出以下异常:

Server Error in '/' Application.

The "WebSecurity.InitializeDatabaseConnection" method can be called only once.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[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) +123
   WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
   WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +52
   MembershipTest2.Filters.SimpleMembershipInitializer..ctor() +193

你有任何想法,这是从哪里来的吗? 如果我调试(本地版本),这个方法只被调用了一次。

谢谢。


3
这怎么算离题了?我也遇到了同样的问题。 - Trevor de Koekkoek
你调用WebSecurity.InitializeDatabaseConnection的代码在哪里? - Nikos
3个回答

17

你可以尝试将调用该方法的语句封装起来,以确保它不会被多次调用。

                if (!WebMatrix.WebData.WebSecurity.Initialized)
                {
                    WebSecurity.InitializeDatabaseConnection(...);
                }

1
我不得不做两次,一次在InitializeSimpleMembershipAttribute的实现中,另一次是在我的ef-migration configuration.cs方法中,我用'InitializeDatabaseConnection'种植了一些预配置的用户/角色。感谢您的想法!有时候简单的解决方案是最好的。 - Ingo
3
注意:InitializedInitializeDatabaseConnection不是线程安全的,你很容易创造出潜在竞态条件。详情请查看这个回答 - Andy Brown

1
在我的情况下,我两者都有。
(在 web.config 中)
<add key="enableSimpleMembership" value="true" />

(在 _ViewStart.cshtml 中)

WebSecurity.InitializeDatabaseConnection("club", "Account", "UserID", "UserName", autoCreateTables: true);

解决方案:看起来你不能同时拥有两个,因此删除一个。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接