【问题标题】:.Net Core NUnit Test project couldn't read value from appconfig.json file with CopyToOutputDirectory.Net Core NUnit 测试项目无法使用 CopyToOutputDirectory 从 appconfig.json 文件中读取值
【发布时间】:2021-07-01 15:31:43
【问题描述】:

我有一个 NUnit 测试项目,我已经创建了配置文件 (appconfig.json) 并获得了 Copy to Output Directory 集:

已检查 .csproj:

  <Content Include="Properties/appconfig.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </Content>
  <Content Include="Properties/launchSettings.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </Content>
</ItemGroup>

然后我创建了一个 ConfigReader 类来从 appconfig.json 文件中获取配置:

public class ConfigReader
    {
        public static string GetSetting(string key)
        {
            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appconfig.json", true, true).Build();
            return configuration["Config:" + key].ToString();
        }
    } 

而且我总是收到如下错误:

System.NullReferenceException: '对象引用未设置为 一个对象的实例。 Microsoft.Extensions.Configuration.IConfiguration.this[string].get 返回 null。

谁能帮我解决这个问题?非常感谢!

【问题讨论】:

    标签: c# .net-core


    【解决方案1】:

    您需要手动更新您的 csproj 以保留最新的我相信。我可以在明天早上确认这一点,因为我遇到了完全相同的问题。这与 csproj 文件有关。

    【讨论】:

    • 嗨@ktbffh,你的意思是我需要手动将所有配置值添加到csproj?我正在使用 netcoreapp3.1 顺便说一句
    • @HCYH 您的答案不正确-您不需要添加它。当你重新编译时,你可能会维护它。尝试这样做 PreserveNewest
    【解决方案2】:

    想通了。需要手动将配置文件放到debug文件夹中。

    【讨论】:

      【解决方案3】:

      如果在调试模式下运行,当 CopyToOutputDirectory 属性设置为 Always 或 PreserveNewest 时,配置文件将复制/替换到以下子文件夹:

      \bin\Debug\netcoreapp3.1\
      

      如果将 CopyToOutputDirectory 选项设置为 Always,则配置文件将始终将配置文件从项目文件夹复制到输出文件夹。

      如果将 CopyToOutputDirectory 选项设置为 PreserveNewest,则如果项目文件夹中的配置文件的时间戳较新,则配置文件将使用项目文件夹中的配置替换输出文件夹中的配置文件,否则不会替换输出中的配置文件 文件夹。

      这就是它对我的工作方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2018-07-17
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多