在一个 aspnetcore 2.0 项目中,我尝试在我的 Web 应用程序和几个 xunit 测试项目中设置一个共享的 appsettings.json 文件。
首先,当我“定期”将 appsettings.json 单独添加到我的项目中时,一切正常。但是,当我尝试添加单个参考/链接如果来自不同路径的文件,则在运行时不会读取这些值。
为了进行设置,我将每个项目的链接文件添加到 .csproj:
<ItemGroup>
<Content Include="..\Shared\appsettings.json">
<Link>appsettings.json</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
在每个构建中,我可以验证它是否很好地输出到/bin/Debug/netcoreapp2.0
目录:
![Screenshot of output directory](https://i.stack.imgur.com/AwGwr.png)
问题是,当读取它时,无论是通过我的 webapi 的默认启动还是在测试中,设置值始终为空。我正在使用强类型配置。在 webapi 项目中,我使用的是WebHost.CreateDefaultBuilder()与 aspnetcore 2.0 约定(在幕后查看hostingEnvironment.EnvironmentName
,dotPeek 告诉我)。
但在测试项目中,也会发生同样的情况。这一切都可以通过我的全局测试装置中的以下示例来解释:
var builder = new ConfigurationBuilder()
// .SetBasePath(???)
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var settings = new FooSettings();
configuration.GetSection("FooSettings").Bind(settings);
if (settings == null) throw new Exception("Could not find or parse 'appsettings.json'");
// The problem: always fails on this check
if (string.IsNullOrEmpty(settings.Bar)) throw new Exception("Could not find or parse 'FooSettings'");
该问题已在上述示例的最后一行进行了注释。同样,当我直接将 appsettings.json 文件添加到项目根目录,而不是将其添加为共享文件夹的链接引用时,它效果非常好。我假设我必须以不同的方式更改 .csproj 配置或使用不同的.SetBasePath(???)
。但对于两者,我都在努力解决如何实现这一目标。
问题:我可以做什么来使linkedappsettings 文件可以在我的所有项目中正确读取吗?
注意:我找到了其他几篇文章,但找不到任何匹配的答案,特别是针对 dotnetcore。