ASP.NET Core Web 3.1 - IIS Express 可以从 localdb 获取数据,但本地 IIS 不能

ASP.NET Core Web 3.1 - IIS Express can fetch data from localdb but local IIS can not

如上所述,我遇到了一个非常奇怪的问题。

代码运行完全一样,唯一不同的是使用的调试配置文件。我正在使用 Microsoft Visual Studio Community 2019 版本 16.6.3.

使用 IIS 配置文件时,代码显示我的数据库中没有媒体。

正在将配置文件切换到 IIS Express,现在我的媒体使用与立即 Windows.

中相同的连接字符串

我首先怀疑 ASP.NET Core Web 3.1 从 appsettings.json 获取连接字符串时出现问题,而 web.config 也需要它。尝试添加它,但没有任何区别。检查 context.Database.GetDbConnection().ConnectionString 也显示两个配置文件相同,所以情况并非如此。

<connectionStrings>
  <add name="DefaultConnection" connectionString="Server=(localdb)\mssqllocaldb;Database=<MYDB>;Trusted_Connection=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
</connectionStrings>

如果我通过 SSMS 查看数据库,我可以按预期看到我的媒体。

IIS 应用程序池以 LocalSystem 运行。如果我切换到像 ApplicationPoolIdentity 这样无权访问数据库的用户,我会在 Windows 事件查看器中收到预期的异常,并且应用程序无法正常启动。

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: SQL Network Interfaces, error: 50

  • Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.

使用 LocalSystem 在事件查看器中一切看起来都很好,但它说我没有媒体或任何其他数据。

使用相同代码的两个相同连接字符串如何显示不同的结果?

尝试将应用程序池身份切换到我知道可以通过 SSMS 访问的当前登录用户:

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: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start. )

根据这个和@nilsK 的评论,我将其修复为:

首先以管理员身份使用 Visual Studio 的 Developer PowerShell 或 Developer Command Prompt,并确认您只有一个 LocalDb 实例。

键入 sqllocaldb info 以查看您的 LocalDb 实例。

然后我关注了这篇文章,应用程序池身份仍然设置为我当前登录的用户,信用:

https://docs.microsoft.com/en-us/archive/blogs/sqlexpress/using-localdb-with-full-iis-part-1-user-profile

在那里我发现将应用程序池的 Load User Profile 设置为 true 是不够的,您还需要将 applicationHost.config 中的 setProfileEnvironment 设置为 true 通常位于C:\Windows\System32\inetsrv\config。使用此配置它有效: