I have 3 environment specific appsettings
files in my .Net core application
in project.json
I have setup publishOptions
like this. ( based on suggestion here)
"publishOptions": { "include": [ "wwwroot", "appsettings.development.json", "appsettings.staging.json", "appsettings.production.json", "web.config" ] },
I have 3 corresponding startup classes that uses appropriate appsettings
based on environment
var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
However when I publish the application then all 3 appsettings files end up in all environments. How do I publish environment specific appsetting file?
If someone else is wondering how to use different appsettings for multiple environments here is a possible solution.
dotnet publish --configuration [Debug|Release]
will copy the appropriate appsettings.json file into the publish folder if *.csproj
has a conditional logic for these files:
.pubxml
publish profile file (can be found in Properties
->PublishProfiles
of Visual Studio) disable that all content files are included by default<PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <EnableDefaultContentItems>false</EnableDefaultContentItems> </PropertyGroup>
<Choose> <When Condition="'$(Configuration)' == 'Debug'"> <ItemGroup> <None Include="appsettings.json" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" /> <None Include="appsettings.prod.json" CopyToOutputDirectory="Never" CopyToPublishDirectory="Never" /> </ItemGroup> </When> <When Condition="'$(Configuration)' == 'Release'"> <ItemGroup> <None Include="appsettings.json" CopyToOutputDirectory="Never" CopyToPublishDirectory="Never" /> <None Include="appsettings.prod.json" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" /> </ItemGroup> </When> </Choose>
Startup.cs
try to load both filespublic Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile($"appsettings.prod.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
I hope this solution, has been helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With