In an aspnetcore 2.0 project I'm trying to setup a single, shared appsettings.json file throughout my web application and several of my xunit test projects.
First off, everything works fine when I add the appsettings.json "regularly" to my projects individually. However, when I attempt to add a single reference/linked file from a different path, the values aren't read out during runtime.
To set this up, for each project I add the linked file to the .csproj:
<ItemGroup>
<Content Include="..\Shared\appsettings.json">
<Link>appsettings.json</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
And on each build, I can verify it is output nicely to the /bin/Debug/netcoreapp2.0
directory:
The problem is that when reading it out, either through the default Startup of my webapi or in the tests, the settings values are always null. I'm using a strong typed configuration. In the webapi project, I'm using the WebHost.CreateDefaultBuilder() with the aspnetcore 2.0 conventions (which under the hood looks at hostingEnvironment.EnvironmentName
, dotPeek tells me).
But also in the case of the test projects, the same occurs. Which all can be explained by the following example in my global test fixture:
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'");
The problem is commented on the last line in the above sample. Again, it works perfect when I directly add the appsettings.json file to the project root, instead of adding it as a linked reference to a shared folder. I am assuming I have to either change the .csproj configuration differently OR use a different .SetBasePath(???)
. But for both I'm struggling on how to achieve it.
The question: What can I do to make the linked appsettings file to be read properly in all my projects?
N.B. I found several other posts, but couldn't find any with a matching answer, specifically for dotnetcore.
来源:https://stackoverflow.com/questions/49888073/values-from-linked-appsettings-json-file-in-dotnet-core-cannot-be-read