3

在访问 [Authorize] 的操作时,我间歇性地遇到以下异常。它似乎有时会起作用,然后有时会失败,但是当我登录并选择“记住我”按钮时,情况肯定更糟。如果我注销,然后立即重新登录,则没有错误,所以下面的文字不能完全准确......这里有一些其他的事情,但我无法识别它。

System.Data.SqlClient.SqlException: 
    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.Web.HttpException (0x80004005): Unable to connect to SQL Server database. ---> System.Web.HttpException (0x80004005): Unable to connect to SQL Server database. ---> System.Data.SqlClient.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)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
   at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
   at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
   at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
   at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
   at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
   at System.Web.Security.RolePrincipal.IsInRole(String role)
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext)
   at System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext)
   at Glimpse.Mvc3.Plumbing.GlimpseAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
   at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

编辑 1

这是请求的 InitializeDatabaseConnection: WebSecurity.InitializeDatabaseConnection("UserDB", "tblPortalUsers", "ID", "UserName", autoCreateTables: false);

编辑 2

我只是注意到堆栈跟踪中间有一些奇怪的东西:

   at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString)
   at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
   at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
   at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
   at System.Web.Security.RolePrincipal.IsInRole(String role)

为什么这段代码试图创建一个 MDF 文件?我的数据位于 SQL 服务器上,连接字符串名称为 UserDB,在 web.config 中定义为:

<connectionStrings>
    <add name="UserDB" connectionString="data source=NORWAY\DEV;initial catalog=SOMEDB;persist security info=True;user id=MYUSER;password=MYPASS" providerName="System.Data.SqlClient" />
    <add name="DALEntities" connectionString="metadata=res://*/DAL.DAL.csdl|res://*/DAL.DAL.ssdl|res://*/DAL.DAL.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=NORWAY\DEV;initial catalog=SOMEDB;persist security info=True;user id=MYUSER;password=MYPASS;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

什么会导致它偏离指定的数据库,并尝试启动一个新的 MDF 来存储会员数据?为什么只有当用户使用他们的“记住我”cookie 重新登录时才会发生这种情况?(我想是的,无论如何......还没有能够证明这一点)

4

2 回答 2

2

查看您的堆栈跟踪,似乎SimpleRoleProvider尚未初始化:

at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)

根据代码,您应该获取此堆栈跟踪的唯一方法是InitializeCalled属性是否为false

public override string[] GetRolesForUser(string username)
{
   if (!InitializeCalled)
   {
       return PreviousProvider.GetRolesForUser(username);
   }
   ...

该内部属性由InitializeRoleProvider的方法设置,WebSecurity方法从方法中调用InitializedDatabaseConnection

您确定WebSecurity.InitializeDatabaseConnection每次应用程序启动时都会执行您的调用吗?

于 2013-02-28T15:12:30.483 回答
0

我认为您的问题与 InitializeSimpleMembership 有关,因为您的所有页面都需要登录。

尝试这个

使用 SimpleMembership 的 IsUserInRole 错误

不要忘记像这样更改您的设置

WebSecurity.InitializeDatabaseConnection("UserDB", "tblPortalUsers", "ID", "UserName", autoCreateTables: true);

因为您将数据库“UserProfile”上的列名更改为“tblPortalUsers”

于 2013-02-28T21:16:03.113 回答