2012-09-09 3 views
11

내 MVC4 컨트롤러의 일부 속성을 인증 추가하기 위해 노력하고있어, 그들은만큼 그것이 내가 역할 필터링 모든 종류의에서 추가 계획 [Authorize] 또는 [Authorize(Users="myuser")],하지만 두 번째의로 잘 작동 그것은 붕괴된다. [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 파일에을하고 가능한 한 빨리 실행되었다 확인했다. 이 다음 비트가 필요하지 않습니다 것 같다 ... 둘째

[InitializeSimpleMembership] 속성을 추가해야합니다 : 라인 주위> InitializeSimpleMembershipAttribute.cs 41

편집 - 코드의 라인 필터에서 찾을 수 있습니다 회원이 될 수있는 클래스에 문제-날이 그들 모두, 그래서 라인에 추가하십시오 app_start 폴더에 FilterConfig.cs 파일에

filters.Add(new InitializeSimpleMembershipAttribute()); 

합니다.

이 두 가지 간단한 변경을 해결 한 것으로 보인다. 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 용 인터넷 템플릿에서 생성 된 InitializeSimpleMembershipAttribute는 개발자가 폼 인증을 사용하지 않는 경우 SimpleMembership 데이터베이스를 느리게로드하도록 설계되었습니다. 양식 인증을 사용하는 경우이 필터를 제거하고 직접 초기화하는 것이 좋습니다. 이것은 article describes how t입니다. 필요에 따라 또한 상단의 수입을 유치했다

[InitializeSimpleMembership] 

을 :

2

는 MVC4에서 나는 내 집 컨트롤러에 주석을 추가 할 수 있었고,이 오류가오고 중지

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로 설정하고 사용할 때 특별히 InitializeSimpleMembershipAttribute 인증 필터를 만들 수도 있습니다. Authorize(Roles="any")