2015-04-14 7 views
1

Недавно я реализовал идентификатор asp.net 2 на веб-сайт MVC. Я после этого прохождение игры здесь, чтобы изменить рк к INT HereПолучение ошибки sql при использовании [Авторизовать (Роли = «Изменить»)]

Каждая вещь, кажется, работает хорошо, я могу назначить пользователям роли следующим образом:

var result = await userManager.AddToRoleAsync(User.Identity.GetUserId<int>(), "Edit"); 

Однако минуту я использую атрибут Авторизовать с ролью, указанной на методе действия, такие как:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    [Authorize(Roles = "Edit")] 
    public async Task<ActionResult> Edit(UdlDownload model) 

Я получаю следующее сообщение об ошибке:

The user instance login flag is not supported on this version of SQL Server. The connection will be closed. 
    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: 

1.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. 
2.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. 
3.Sql Server Express must be installed on the machine. 
4.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): The user instance login flag is not supported on this version of SQL Server. The connection will be closed.] 
    System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5341687 
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +546 
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1693 
    System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69 
    System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30 
    System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317 
    System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +892 
    System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +311 
    System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +646 
    System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5356769 
    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 oldConnection, DbConnectionInternal& connection) +5358970 
    System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146 
    System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16 
    System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94 
    System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110 
    System.Data.SqlClient.SqlConnection.Open() +96 
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75 

[HttpException (0x80004005): Unable to connect to SQL Server database.] 
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +130 
    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 

Вот мой StartUp.Auth

public void ConfigureAuth(IAppBuilder app) 
     { 
      // Configure the db context, user manager and signin manager to use a single instance per request 
      app.CreatePerOwinContext(IdentityDbContext.Create); 
      app.CreatePerOwinContext<FskUserManager>(FskUserManager.Create); 
      app.CreatePerOwinContext<FskSignInManager>(FskSignInManager.Create); 
      app.CreatePerOwinContext<FskRoleManager>(FskRoleManager.Create); 

      // Enable the application to use a cookie to store information for the signed in user 
      // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
      // Configure the sign in cookie 
      app.UseCookieAuthentication(new CookieAuthenticationOptions 
      { 
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
       LoginPath = new PathString("/Account/Login"), 
       Provider = new CookieAuthenticationProvider 
       { 
        // Enables the application to validate the security stamp when the user logs in. 
        // This is a security feature which is used when you change a password or add an external login to your account. 
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<FskUserManager, FskUser, int>(
       validateInterval: TimeSpan.FromMinutes(30), 
       regenerateIdentityCallback: (manager, user) => 
        user.GenerateUserIdentityAsync(manager), 
       getUserIdCallback: (id) => (id.GetUserId<int>())) 

        //OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<FskUserManager, FskUser,int>(
        // validateInterval: TimeSpan.FromMinutes(30), 
        // regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
       } 
      }); 
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 
} 

Что вызывает мой вопрос? Я чувствую, что я упустил важный шаг, когда я рассказываю инфраструктуре asp.net использовать мой RoleStore, а не его по умолчанию.

Вот моя строка соединения:

<add name="IdentityDbContext" connectionString="Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=FSK_FskNetworks;persist security info=True;user id=sa;[email protected];MultipleActiveResultSets=True;application name=EntityFramework" providerName="System.Data.SqlClient" /> 

После добавления <clear/> выше моей строки подключения.

Configuration Error 
    Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty. 

Source Error: 



Line 236:  <membership> 
Line 237:   <providers> 
Line 238:    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/> 
Line 239:   </providers> 
Line 240:  </membership> 


Source File: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config Line: 238 
+1

Это работает, если вы добавляете '' строка над строкой подключения? – DavidG

+0

После добавления '' Я не получаю другую ошибку. Я добавлю к моему вопросу. – Zapnologica

+0

его не в моем web.config ... если вы посмотрите на сообщение об ошибке со ссылкой на machine.config по какой-то нечетной причине? – Zapnologica

ответ

4

Вашего файл machine.config уже содержит определенные значения, такие как строки подключения, поставщик членства и настройки менеджера роли и файл web.config наследует все параметры там.

Файл machine.config на вашем компьютере настроен для добавления поставщика членства с использованием строки подключения, которая называется LocalSqlServer. Поэтому, когда вы используете атрибут Authorize, он сначала пытается использовать этого провайдера вместо Identity. То же самое касается менеджера ролей.

Вы можете отключить эту функцию, очищая существующих поставщиков в вашем web.config так:

<configuration> 
    .... 
    <system.web> 
     ... 
     <membership> 
      <providers> 
       <clear/> 
      </providers> 
     </membership> 
     <roleManager enabled="false" /> 
    </system.web> 
</configuration> 

Кроме того, вы можете добавить это к вашему appSettings:

<appSettings> 
    <add key="enableSimpleMembership" value="false" /> 
</appSettings> 
+0

Под каким разделом я хотел добавить членство? '' – Zapnologica

+0

Это нормально? Почему я никогда не видел упоминания о Machine.config, выполняющем его в любых учебниках? это странный случай, который происходит на моем компьютере? Могу ли я не просто полностью игнорировать конфигурацию машины? Могу ли я удалить его? – Zapnologica

+1

Это довольно часто. Конфигурация машины требуется, но может отличаться на машинах. Вероятно, зависит от того, какая версия IIS установлена. – DavidG

Смежные вопросы