Dotnet 核心应用程序无法使用 IIS 连接到 SQL 服务器,仅当使用 IIS Express 或 Kestrel 时

Dotnet core application cannot connect to SQL server using IIS, only when using IIS Express or Kestrel

我有一个 .NET Core Web 应用程序,它从 SQL 服务器获取一些数据。我通过互联网连接到 SQL 服务器。

当我 运行 使用 IIS Express 或 Kestrel 的应用程序时,我可以连接到数据库服务器并检索数据。我也可以使用 SQL Server Management Studio 成功连接到数据库服务器。

这是我正在使用的连接字符串:

"ConnectionStrings": {
    "DefaultConnection": "Server=my-sql-server.someurl.com; Initial Catalog=my-sql-database; User ID=my-user-id; Password=my-password;"
}

但是 当我在 IIS 中尝试 运行 同一个网站,在同一台机器上时,我收到以下错误消息:

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: TCP Provider, error: 0 - No such host is known.)

我怀疑这与 dotnet core/IIS 组合有关,而不是 firewall/network/authentication 问题,但我可能错了。

您需要在 sql 服务器上启用 TCP/IP 协议。请使用以下 link: Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

问题只是我查看了错误的连接字符串。

我有 appsettings.json 包含一个连接字符串,appsettings.Production.json 包含另一个。

当运行使用IIS Express或Kestrel安装应用程序时,使用第一个,但是当我发布应用程序然后运行它在IIS下时,环境设置为Production,并改用生产设置。

问题是生产连接字符串指向一个不再存在的数据库服务器。

我通过将 LocalSystem 添加到网站 Application pool 中的 Identity 解决了这个问题。

步骤:

  1. Select网站申请池
  2. 右键点击高级设置
  3. 点击 Identity,并将其更改为 LocalSystem