找不到或无法从 IIS 访问 SQL Server

我已在 .NET 5.0 上部署了我的 IIS 应用程序,这是一个基本的 API 并具有 context and controllers。 Context 有一个定义好的配置,它有连接字符串:

    protected override void Onconfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=localhost;Database=flutter;");
        optionsBuilder.EnableSensitiveDataLogging();
    }

当我在本地托管我的应用程序时一切正常,请求也很好,但是一旦我尝试在我的服务器上调用 API,它就会失败。

调用默认的 API 调用返回 200 OK

找不到或无法从 IIS 访问 SQL Server

但是一旦我调用从数据库中获取数据的端点,我就会得到 500

找不到或无法从 IIS 访问 SQL Server

由于我在调用后检查了 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,TimeoutTimer timeout,Boolean withFailover) at microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo,Boolean redirectedUserInstance,SqlConnectionString connectionOptions,SqlCredential credential,TimeoutTimer timeout) at microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout,Boolean redirectedUserInstance) at microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,Object providerInfo,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,DbConnectionOptions userOptions) at microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject,DbConnectionOptions userOptions,DbConnectionInternal oldConnection) at microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject,DbConnectionInternal oldConnection) at microsoft.Data.ProviderBase.DbConnectionPool.Trygetconnection(DbConnection owningObject,UInt32 waitForMultipleObjectsTimeout,Boolean allowCreate,Boolean onlyOneCheckConnection,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,Boolean isCompleted) at microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker,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 访问 SQL Server

我已将所需用户(在我看来)添加到数据库的登录名

找不到或无法从 IIS 访问 SQL Server

我的 IIS 设置如下所示:

找不到或无法从 IIS 访问 SQL Server

我的应用程序池设置如下

找不到或无法从 IIS 访问 SQL Server

过去几天我一直在网上搜索并尝试不同的方法来解决这个问题,但我就是做不到。我在 IIS 上尝试了不同的设置、不同的方法、不同的服务器,但无法使其工作。急切求助。提前致谢。

编辑 1: 将 SQL Server 更新到最新的 CU 版本

beautytai 回答:找不到或无法从 IIS 访问 SQL Server

您的连接字符串有问题。无需密码即可使用集成安全性

optionsBuilder.UseSqlServer(@"Data Source=localhost;Initial catalog=flutter;Persist Security Info=True;Integrated Security=SSPI;");

或者添加一个带有密码的用户帐户到 SQL server security 并使用这个

@"Data Source=localhost;Initial catalog=flutter;Integrated Security=False;User ID=..;Password=...;"

这个变体更加灵活,因为您可以定义一组所有需要的权限。

并且由于您使用的是 net core,因此您必须为您的 web api 添加一个特殊的池。例如,称之为 FlatterApi。在高级设置中,将“Net Clr Version”更改为“No Managed Code”,“Identity”更改为“App Ppool Idenity” 选择此池作为您的网络应用程序的应用程序池。

使用 sql management studio 添加到 Flatter db 安全新帐户(无需登录)并键入 IIS APPPOOL\FlatterApi 作为帐户名并选择此数据库的所有权限

,

您应该打开Sql配置设置(搜索它),然后允许TCP连接。 要测试自己,请创建一个空文本文件,将扩展名更改为 .udl,双击它,配置连接,保存,然后使用文本编辑器打开该文件以查看正确的连接字符串。

,

所以我已经设法解决了这个问题,但我不确定哪个解决方案实际上解决了它,因为我在发布应用程序时有点搞砸了,所以一些更改没有进入 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 服务(服务器、服务器浏览器、服务器代理)。不确定是否错过了任何其他步骤,但希望它有所帮助。谢谢大家

本文链接:https://www.f2er.com/5385.html

大家都在问