2012-09-09 75 views
11

我試圖添加授權屬性給我的一些MVC4控制器,他們工作得很好,只要它是一個計劃[Authorize][Authorize(Users="myuser")],但第二個我添加任何類型的角色過濾它分崩離析,例如。 [Authorize(Roles="admin")]。然後我開始得到如下錯誤:SimpleMembership,MVC4,AuthorizeAttribute和Roles

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]屬性需要添加任一類別,其中的成員可能是一個問題,對我來說這就是所有的人,所以我加了一行:

filters.Add(new InitializeSimpleMembershipAttribute()); 

在app_start文件夾中的文件FilterConfig.cs。

這兩個簡單的改變似乎已經修復了它。我相信我可以對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

嘿@迪蘭它爲我和乾杯做了詭計!現在已經掙扎了好幾天了。 –

6

您不需要移動第一行。我測試只需添加過濾器

filters.Add(new InitializeSimpleMembershipAttribute()); 

但如果你正在創建你需要登錄一個網站你可以擁有它是一個控制器上,而不必把它所有的控制器。

2

由MVC 4的Internet模板生成的InitializeSimpleMembershipAttrribute設計用於在開發人員不使用表單身份驗證的情況下延遲加載SimpleMembership數據庫。如果您使用表單身份驗證,建議刪除此過濾器並直接對其進行初始化。這article describes how t o做到這一點。

2

在MVC4我能夠添加註釋到我家控制器和這個錯誤就不來了:

[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")

相關問題