【问题标题】:Splitting the configuration file leads to exception in System.Configuration.dll拆分配置文件会导致 System.Configuration.dll 出现异常
【发布时间】:2025-12-24 05:30:12
【问题描述】:

我有一个 MVC .NET 应用程序。该解决方案包含应用程序本身和一个单元测试项目,其中还包含集成测试(包括需要数据库连接的数据层测试)。

我决定将两个项目的连接字符串放在一个单独的配置文件中。我将<connectionStrings>标签的内容复制到一个新文件中,并在web项目的Web.config文件和测试项目的app.config文件中使用了configSource属性。 Web 项目像以前一样调试和运行。测试项目无法调试,退出

'vstest.executionengine.x86.exe'(托管 (v4.0.30319)):已加载 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration.resources\v4.0_4.0.0.0_de_b03f5f7f11d50a3a\ System.Configuration.resources.dll'

System.Configuration.dll 中发生了“System.Configuration.ConfigurationErrorsException”类型的第一次机会异常

当我尝试运行它时,所有测试都失败了。当我使用原始版本的 app.config 文件时,它们通过了。

这是适用的 app.config 版本:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
  <connectionStrings>
    <add name="TumorModelsDB" connectionString="Data source=tsql2; Initial Catalog=TumorModelle; User Id=anonymized; Password=anonymized;" providerName="System.Data.SqlClient" />
    <add name="AzaraIntegrationTest" connectionString="Data Source=tsql2;Initial Catalog=AzaraIntegrationTest;User Id=anonymized; Password=anonymized;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

这是不工作的版本(与其他项目工作的 web.config 基本相同):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
  <connectionStrings configSource="ConnectionStrings.config" />
</configuration>

(完整)新的 ConnectionStrings.config 文件是:

  <connectionStrings>
    <add name="TumorModelsDB" connectionString="Data source=tsql2; Initial Catalog=TumorModelle; User Id=anonymized; Password=anonymized;" providerName="System.Data.SqlClient" />
    <add name="AzaraIntegrationTest" connectionString="Data Source=tsql2;Initial Catalog=AzaraIntegrationTest;User Id=anonymized; Password=anonymized;" providerName="System.Data.SqlClient" />
  </connectionStrings>

ConnectionStrings.config 文件的内容与连接字符串标记的旧内容完全相同。 configSource 属性中的文件名没有拼写错误。 ConnectionStrings.config 文件存在于测试项目中(它不是来自 Web 项目的链接)。 Build Action 设置为 Content,Copy to Output 设置为 Do not copy。我没有想法在哪里寻找问题的根源。有什么想法吗?

【问题讨论】:

    标签: .net asp.net-mvc web-config app-config


    【解决方案1】:

    我设法找到了解决方案。

    尽管this answer 的cmets 说正确的设置是“不复制”,但将其设置为“始终复制”解决了问题。现在项目按预期运行和调试。

    当其文件设置为始终复制时,Web 项目也可以正常运行。当我将包含的文件替换为指向 Web 项目的连接设置文件的链接时,这很有用,正如我从一开始就打算的那样。

    分步解决方案:在配置文件中,选择“属性”。在“属性”窗口中,将“输出时复制”设置的值更改为“始终复制”。

    【讨论】:

      最近更新 更多