【问题标题】:Getting sql error when using [Authorize(Roles = "Edit")]使用 [Authorize(Roles = "Edit")] 时出现 sql 错误
【发布时间】:2015-04-14 21:15:53
【问题描述】:

我最近在一个 MVC 网站中实现了 asp.net identity 2。我按照这里的演练将我的 pk 更改为 INT Here

一切似乎都很好,我可以将用户分配给如下角色:

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

但是,当我将 Authorize 属性与在操作方法上指定的角色一起使用时,例如:

    [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;password=p@ssword;MultipleActiveResultSets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />

在我的连接字符串上方添加&lt;clear/&gt; 之后。

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 

【问题讨论】:

  • 在连接字符串上方添加&lt;clear/&gt;行是否有效?
  • 添加 &lt;clear/&gt; 后,我没有收到其他错误。我将添加到我的问题中。
  • 它不在我的 web.config 中......如果您查看错误消息,它出于某种奇怪的原因引用了 machine.config?
  • 哦,是的,然后将另一个 &lt;clear/&gt; 添加到您的 web.config 以删除会员提供程序。
  • 明确与我的错误有什么关系?所以我可以试着理解你认为可能是什么问题?连接字符串可以与身份系统的其余部分一起使用吗?

标签: c# asp.net asp.net-mvc asp.net-identity-2


【解决方案1】:

您的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>

【讨论】:

  • 我打算在哪个部分添加会员? ` `
  • 这正常吗?为什么我从未在任何教程中看到任何提及 Machine.config 影响它的内容?这是我电脑上发生的奇怪情况吗?我不能完全忽略机器配置吗?不能删吗?
  • 这很常见。机器配置是必需的,但在机器上可能会有所不同。这可能取决于安装的 IIS 版本。
  • 现在我在机器配置中遇到另一个错误,Line 246: &lt;roleManager&gt; Line 247: &lt;providers&gt; Line 248: &lt;add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; Line 249: &lt;add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; Line 250: &lt;/providers&gt; Line 248
猜你喜欢
  • 2013-09-06
  • 1970-01-01
  • 2014-10-08
  • 2023-02-02
  • 1970-01-01
  • 2013-07-17
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多