How we can change publish configuration to publish a different version of a file based on settings

618 Views Asked by At

Can you explore how we can change the publish configuration to publish a different version of a file based on these settings“

I.e., We have three versions of the file: EmailConfig.json (dev), EmailConfig.Uat.json (uat), and EmailConfig.Live.json (live).

Depending on the settings, the correct version of the file will get published as EmailConfig.json.

1

There are 1 best solutions below

0
On

You can not do what you are asking. It is not possible to publish different versions of your json file. You can find the documentation of pubish command here: https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-publish

What I would do if I were you is that I would pass the content of the EmailConfig file into the appsettings file, as a "sub-object" like:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "EmailConfig": {
    "YourProperty1": "",
    "YourProperty2":  ""
  },
  "AllowedHosts": "*"
}

I would create one version of this appsettings file for each environment I want to deploy, with the environment name, like appsettings.dev.json, appsettings.live.json, etc.Then in the StartUp constructor you add the following:

    var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    var confBuilder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env}.json", true)
            .AddEnvironmentVariables();

In this way you will always override the values of the appsettings.json file with the values for the specific environment file.

Finally in order to have the right ASPNETCORE_ENVIRONMENT variable in your machine running the application, you either set the variable on each machine, or you can even push the environment name as part of the publish configuration (as you would like too from the beginning) like:

dotnet publish /p:Configuration=Release /p:EnvironmentName=Development

you can check: How to change hardcoded variables basing on publish configuration?