How to publish environment specific appsettings in .Net core app?

LP13 picture LP13 · Aug 31, 2016 · Viewed 37.5k times · Source

I have 3 environment specific appsettings files in my .Net core application

enter image description here

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?

Answer

Ben picture Ben · Jan 16, 2019

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:

  • First in the .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>
  • Then specify conditional Debug/Release logic
<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>
  • Finally inside Startup.cs try to load both files
public 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.