【发布时间】: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。
谁能帮我解决这个问题?非常感谢!
【问题讨论】: