在 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
目录:问题是,在读取它时,无论是通过我的 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(???)
.但对于两者,我都在努力实现它。问题:我该怎么做才能使 已链接 appsettings 文件可以在我的所有项目中正确读取吗?
注意我找到了其他几个帖子,但找不到任何具有匹配答案的帖子,特别是针对 dotnetcore。
最佳答案
我在 Program
中添加了一些代码后它开始工作了(感谢@mr_squall 的指导..):
public static void Main(string[] args)
{
CreateHostBuilder(args)
#if !DEBUG
.UseContentRoot(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
#endif
.Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
关于c# - 无法读取 dotnet 核心中链接的 appsettings.json 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888073/