Merge appsettings.{env}.json into appsettings.json in .NET Core 3.1

153 views Asked by At

I understand the default behavior in .NET Core 3.1 is that when you publish your solution, it copies over all your appsettings.{env}.json files into the final package, and it is up to your environment variable to determine which one will be taken into account at run time.

However, due to a situation regarding some badly setup legacy systems, I need to find a way to make the publishing behave similar to that of the old .NET Framework, where you could have multiple Web.{env}.Config files and when you published, depending on the config parameter you passed, one final web.config was generated which was the result of merging the web.env.config and the general web.config.

I need to implement the exact same behavior with appsettings.json when publishing a .NET Core 3.1 project.

Is that possible? And how?

1

There are 1 answers

0
Brando Zhang On

Asp.net core's appsttings is totally different than the web.config. One is json file another is xml file.

Besides, according to this github issue, you could find Asp.net core program team also don't want to implement this thing.

Here is a workaround, this workaround is not merg, just replace the appsetting.json according to the replace one.

So for all the appsetting.env.json, you need to put all the settings inside it.

You could modify the csporj file by adding below codes:

<ItemGroup>
    <Content Update="appsettings*json" CopyToPublishDirectory="Never" />
    <FileToRename Include="$(ProjectDir)appsettings.Release.json" />
</ItemGroup>
<Target Name="RenameAppSettingsProd" AfterTargets="Publish">
    <Message Text="Inside AfterPublish" Importance="high" />
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="$(PublishDir)appsettings.json" OverwriteReadOnlyFiles="true" />
</Target>

Then it just generate one appsettings.json file according to publish environment.

Like below:

I put a specific settings inside the appsetting.release.json.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "settings": "release"
}

Result:

enter image description here