找不到或无法从 IIS 访问 SQL Server
Posted
技术标签:
【中文标题】找不到或无法从 IIS 访问 SQL Server【英文标题】:SQL Server is not found or accessible from IIS 【发布时间】:2021-07-31 12:38:00 【问题描述】:我在IIS
上部署了我的.NET 5.0
应用程序,这是一个基本的API
并具有context and controllers
。上下文有一个定义的配置,它有连接字符串:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer(@"Server=localhost;Database=flutter;");
optionsBuilder.EnableSensitiveDataLogging();
在本地托管我的应用程序时一切正常,并且请求运行良好,但一旦我尝试在我的服务器上调用 API
,它就会失败。
调用默认的API
调用返回200 OK
但只要我调用从数据库中获取数据的端点,我就会得到500
我在通话后检查了Event Viewer
,发现一个错误:
Category: Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer EventId: 2 SpanId: 73e6b4810067764d TraceId: 2c38235f0fa745438ce6ecdcf1874c44 ParentId: 0000000000000000 RequestId: 80000072-0001-fe00-b63f-84710c7967bb RequestPath: /FlutterAPI/api/Users/5 Connection ID "18302628891539275888", Request ID "80000072-0001-fe00-b63f-84710c7967bb": An unhandled exception was thrown by the application. Exception: Microsoft.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: SNI_PN11, error: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (87): The parameter is incorrect. at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action``1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen() --- End of stack trace from previous location --- at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable``1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func``4 operation, Func``4 verifySucceeded, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable``1.AsyncEnumerator.MoveNextAsync() at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable``1 asyncEnumerable, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable``1 asyncEnumerable, CancellationToken cancellationToken) at FlutterApi.Controllers.UsersController.GetUser(Int64 id) in G:\Projects\flutter_api\ApiFlutter\Controllers\UsersController.cs:line 39 at lambda_method6(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask``1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT``1.ProcessRequestAsync() ClientConnectionId:00000000-0000-0000-0000-000000000000 Error Number:87,State:0,Class:20
我的 SQL Server 已启动并正在运行
我已将必需的用户(在我看来)添加到数据库的登录中
我的 IIS 设置如下所示:
我的应用程序池设置如下所示
在过去的几天里,我一直在网上搜索并尝试不同的方法来解决这个问题,但我就是做不到。我在 IIS 上尝试了不同的设置、不同的方法、不同的服务器,但无法使其正常工作。急于求救。提前致谢。
编辑 1: 将 SQL Server 更新到最新的 CU 版本
【问题讨论】:
仅供参考,我真的建议更新您的实例;您在运行 RTM 版本时落后了大约 3 年。 @Larnu 实例是什么? 您的 SQL Server 实例。这是 2019 年的 RTM。 @KęstutisRamulionis,见Solving Connectivity errors to SQL Server 不,@KęstutisRamulionis,你的更新是 3 年未应用的更新。最新的是 CU11,15.0.4138.2,或者如果你反对 CU,那么最新的 GDR 版本是 15.0.2080.9。 【参考方案1】:您的连接字符串有问题。无需密码即可使用集成安全性
optionsBuilder.UseSqlServer(@"Data Source=localhost;Initial catalog=flutter;Persist Security Info=True;Integrated Security=SSPI;");
或将带有密码的用户帐户添加到 SQL Server 安全性并使用此
@"Data Source=localhost;Initial catalog=flutter;Integrated Security=False;User ID=..;Password=...;"
这个变体更加灵活,因为您可以定义一组所有需要的权限。
而且由于您使用的是网络核心,因此您必须为您的 web api 添加一个特殊的池。例如,称之为 FlatterApi。在高级设置中将“Net Clr Version”更改为“No Managed Code”,将“Identity”更改为“App Ppool Idenity” 选择此池作为您的 Web 应用程序的应用程序池。
使用 sql management studio 添加到 Flatter db 安全新帐户(无需登录)并键入 IIS APPPOOL\FlatterApi 作为帐户名并选择此 db 的所有权限
【讨论】:
两种方法都试过了,还是不行,还是一样的错误。 @KęstutisRamulionis 检查我的更新答案 我无法创建该配置文件,显然它只是不允许我说它不存在【参考方案2】:您应该打开 Sql 配置设置(搜索它),然后允许 TCP 连接。 要测试自己,请创建一个空文本文件,将扩展名更改为 .udl,双击它,配置连接,保存,然后使用文本编辑器打开文件以查看正确的连接字符串。
【讨论】:
我得到了几乎相同的字符串,但没有服务器.. 目前仍然无法正常工作 你能与UDL文件建立连接吗?【参考方案3】:所以我已经设法解决了这个问题,但我不确定哪个解决方案真正解决了这个问题,因为我有点搞砸了发布应用程序,所以一些更改没有进入 IIS,最后全部发布了。首先,我将把我的连接字符串留给将来有问题的人:
Server=DESKTOP-******;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=yourDB;
然后我只是将我的连接字符串迁移到 appsettings.json (不确定这个是否有任何影响)
然后在我的 DefaultAppPool 上,我选择了 ApplicationPoolIdentity 作为 Identity 并且有一个错误,我没有从表中选择的权限,所以我将用户 IIS APPPOOL\DefaultAppPool
添加到我的 SQL Server -> Security -> Logins,显然它有效。还启动了所有 SQL Server 服务(服务器、服务器浏览器、服务器代理)。不确定是否错过了任何其他步骤,但希望它有所帮助。谢谢大家
【讨论】:
几乎可以肯定这是启动服务的最后一步,因为您没有收到登录错误,只有连接错误以上是关于找不到或无法从 IIS 访问 SQL Server的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server Management Studio 17找不到一个或多个组件