The configuration file 'appsettings.json' was not found and is not optional
In later .net core versions a *.csproj file is used instead of the project.json file.
You can modify the file to get the desired result by adding:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
In My case the file appsettings.json
existed in project folder, but it was set to Do not copy
, I changed the setting to Copy always
(see images below). And it worked for me.
It will automatically added following XML to your project.csproj
file:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
I have looked at other answer, project.json
is dead as this answer says.
In your project.json
ensure you have inlcuded appsettings.json
as a copyToOutput
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true,
"copyToOutput": {
"include": [ "appsettings.json" ]
}
},
For me the error was using Directory.GetCurrentDirectory()
. This worked fine running locally but on a production server it failed when the program was started from Powershell
. Replaced with Assembly.GetEntryAssembly().Location
and everything worked.
Complete code:
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = builder.Build();