2012-09-09 6 views
11

MVC4コントローラのいくつかに権限属性を追加しようとしていますが、計画が[Authorize]または[Authorize(Users="myuser")]であれば正常に動作しますが、2番目のロールフィルタリングはすべて追加しますそれはばらばらになります。 [Authorize(Roles="admin")]。私は次のようなエラーが出るようになります。SimpleMembership、MVC4、AuthorizeAttributeおよびロール

Server Error in '/' Application.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

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.

SQLExpress database file auto-creation error:

The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:

If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102 . If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist. If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database. Sql Server Express must be installed on the machine. The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.

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:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +5295167 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5307115
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5309659
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource
1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +5311874
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource 1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource
1 retry) +83 System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76

[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

私は本当に何が起こっているのか分かりません。繰り返しますが、authorize属性のロールビットを削除しても、権限のないユーザーを少なくとも止める限りはうまくいきますが、管理者のユーザーをアプリにハードコードする必要がある場合はうまくいきません。

何が起こっているのか、どうすれば正しく動作させることができますか?

おかげで、

+0

ロール/グループのスペルは正しいですか? –

答えて

14

私は(私はそれを行うためのより良い方法があります確信しているが)解決策を見つけました。まず、SimpleMembershipによって使用されるデータベースは十分に早く初期化されていないので、私はライン移動:

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

Global.asaxファイルにし、それは可能な限り早期に実行してしまったことを確認しました。コードの行は、フィルタで見つけることができます - > InitializeSimpleMembershipAttribute.cs、ライン41

編集周り:この次のビットが必要ではないようだ...

は、第二に、[InitializeSimpleMembership]属性を追加する必要があります会員が問題-私かもしれない任意のクラスにそれはそれらのすべてですので、私はラインを追加しました:app_startフォルダ内のファイルFilterConfig.csに

filters.Add(new InitializeSimpleMembershipAttribute()); 

を。

これらの2つの簡単な変更は、それを修正したようです。私はMVC4に含まれているSimpleMembershipの一般的な動作にいくつかの改善があると確信しています。それは非常によく書かれているようではありません(ハードコードされた接続文字列など)。 SimpleMembershipのものを最初に書いたことで修正されました!

+1

+1ありがとうございます。あなたの解決策は私にとって問題を解決しました。また、この問題に遭遇した他の人のためにこの記事を見つけました:http://stackoverflow.com/questions/12257232/role-based-authentication-in-the-new-mvc-4-internet-template-using-simplemembers?rq= 1 –

+0

ちょっと@Dylanそれは私のためのトリックと乾杯!今、数日間これを苦労していた。 –

6

最初の行を移動する必要はありません。私はあなたがログインする必要があり、サイトを作成している場合はあなただけのコントローラのすべての上に配置する必要があり、1つのコントローラ上で、それを持ってすることはできませんが、単にフィルターに

filters.Add(new InitializeSimpleMembershipAttribute()); 

を添加することによって試験しました。

2

MVC 4用のインターネットテンプレートによって生成されたInitializeSimpleMembershipAttributeは、開発者がフォーム認証を使用していない場合にSimpleMembershipデータベースの遅延読み込み用に設計されています。フォーム認証を使用している場合は、このフィルタを削除して直接初期化することをお勧めします。これはarticle describes how tです。

MVC4で
2

私は私のホームコントローラに注釈を追加することができたと、このエラーが来る停止:

[InitializeSimpleMembership] 

はまた、必要に応じて上部の輸入に持っていた:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Transactions; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Security; 
using DotNetOpenAuth.AspNet; 
using Microsoft.Web.WebPages.OAuth; 
using WebMatrix.WebData; 
1

チェックInitializeSimpleMembershipAttribute用法、ウェブ。設定をSimpleProvidersに設定することもできます。Authorize(Roles="any")

関連する問題