2012-09-09 4 views
11

Tôi đang cố gắng thêm các thuộc tính ủy quyền cho một số bộ điều khiển MVC4 của tôi, và chúng hoạt động tốt miễn là nó là một gói [Authorize] hoặc [Authorize(Users="myuser")], nhưng thứ hai tôi thêm vào bất kỳ loại lọc vai trò nào nó sụp đổ, ví dụ. [Authorize(Roles="admin")]. Sau đó tôi bắt đầu nhận được các lỗi như:SimpleMembership, MVC4, AuthorizeAttribute and 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

Tôi thực sự không chắc chắn những gì đang diễn ra ở đây. Một lần nữa, nếu tôi xóa bit vai trò của thuộc tính ủy quyền, thì nó hoạt động tốt (ít nhất là ngăn chặn người dùng trái phép) nhưng không tốt nếu tôi phải mã hóa cứng người dùng quản trị vào ứng dụng!

Bất kỳ ý tưởng nào đang xảy ra ở đây và cách tôi có thể làm cho quảng cáo hoạt động bình thường?

Cảm ơn,

+0

Bạn có chắc chắn chính tả của vai trò/nhóm đó là đúng không? –

Trả lời

14

Tôi đã tìm thấy giải pháp (mặc dù tôi chắc chắn có cách tốt hơn để thực hiện). Thứ nhất, cơ sở dữ liệu được sử dụng bởi SimpleMembership không được khởi tạo đủ sớm, vì vậy tôi chuyển dòng:

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

đến tập tin Global.asax và chắc chắn nó đã chạy càng sớm càng tốt. Các dòng mã có thể được tìm thấy trong Filters -> InitializeSimpleMembershipAttribute.cs, xung quanh dòng 41

Edit: có vẻ như bit tiếp theo này là không cần thiết ...

Thứ hai, các thuộc tính [InitializeSimpleMembership] cần phải được thêm cho bất kỳ lớp học, nơi thành viên có thể là một vấn đề đối với tôi-đó là tất cả trong số họ, vì vậy tôi đã thêm dòng:

filters.Add(new InitializeSimpleMembershipAttribute()); 

đến tập tin FilterConfig.cs trong thư mục app_start.

Hai thay đổi đơn giản này dường như đã sửa đổi. Tôi chắc rằng có một số cải tiến mà tôi có thể thực hiện đối với các hoạt động chung của các công cụ SimpleMembership trong MVC4 mặc dù nó có vẻ không được viết tốt (các chuỗi kết nối được mã hóa cứng vv!), Vì vậy có thể là các vấn đề này có thể cố định bằng cách làm cho công cụ SimpleMembership được viết tốt ngay từ đầu!

+1

+1 Cảm ơn vì điều này. Giải pháp của bạn đã giải quyết được vấn đề cho tôi. Cũng tìm thấy bài đăng này cho bất kỳ ai khác truy cập vấn đề này: http://stackoverflow.com/questions/12257232/role-based-authentication-in-the-new-mvc-4-internet-template-using-simplemembers?rq= 1 –

+0

Hey @Dylan nó đã làm các trick cho tôi và Cheers !! Đã đấu tranh này trong vài ngày nay. –

6

Bạn không cần phải di chuyển dòng đầu tiên. Tôi đã thử nghiệm bởi chỉ cần thêm các bộ lọc

filters.Add(new InitializeSimpleMembershipAttribute()); 

Mặc dù nếu bạn đang tạo một trang web yêu cầu bạn đăng nhập bạn chỉ có thể có nó trên rằng một bộ điều khiển và không cần phải đặt nó trên tất cả các bộ điều khiển.

2

InitializeSimpleMembershipAttrribute được tạo bởi mẫu Internet cho MVC 4 được thiết kế để tải chậm cơ sở dữ liệu SimpleMembership trong trường hợp nhà phát triển không sử dụng xác thực biểu mẫu. Nếu bạn đang sử dụng xác thực biểu mẫu, bạn nên xóa bộ lọc này và khởi tạo nó trực tiếp. Điều này article describes how t o làm điều này.

2

Trong MVC4 tôi đã có thể thêm chú thích để kiểm soát nhà tôi và lỗi này ngừng mọc lên:

[InitializeSimpleMembership] 

Cũng đã phải mang trong nhập khẩu ở phía trên khi cần thiết:

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

Kiểm tra InitializeSimpleMembershipAttribute cách sử dụng, web.cài đặt cấu hình cho SimpleProviders và cũng có thể xem xét việc làm cho Bộ lọc ủy quyền InitializeSimpleMembershipAttribute đặc biệt khi sử dụng Authorize(Roles="any")