2

For my ASP.NET core solution, I have an appsettings.json file and it looks like this

{
  "Branch": {
    "Name": "test"
  },
}

If I want to replace value for "Branch.Name" to some other text, for example "prod" at build time. How do I achieve that?

EDIT: I am aware of the "ASPNETCORE_ENVIRONMENT" environment variable and environment-specific appsettings file for .net core. But unfortunately, for some reason hard to explain, I still need to set value for a key in "appsettings.json" file at build time...

sean717
  • 11,759
  • 20
  • 66
  • 90

2 Answers2

2

This is not how configuration works in ASP.NET Core. It works on an override system, so instead of literally changing values, you override those values with a more prominent source.

By default, appsettings.json is actually the least priority config source. It can be overridden by all of environment-specific JSON (appsettings.Production.json for example), environment variables, and/or command-line arguments.

For the purposes here, you should be looking at environment-specific JSON and/or environment variables. For example, if you create an appsettings.Production.json with contents:

{
  "Branch": {
    "Name": "prod"
  },
}

And then set your deployment environment to Production (i.e. ASPNETCORE_ENVIRONMENT environment variable), then Branch.Name will be prod in that environment. Similarly, you can set a Branch:Name environment variable to prod, and this will also override the value.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Sorry I forgot to mention that I am aware of the "ASPNETCORE_ENVIRONMENT" environment variable and environment-specific appsettings file for .net core. But unfortunately, for some reason hard to explain, I still need to set value for a key in "appsettings.json" file at build time... – sean717 Sep 17 '19 at 21:09
  • There is no mechanism for that. Therefore, it's probably a better idea to focus on the problem of why you think you have to, because there shouldn't be a need. – Chris Pratt Sep 17 '19 at 21:22
1

Yes, there is no built-in way to do this. I end up solving this by using jq. Read the answer of this question.

sean717
  • 11,759
  • 20
  • 66
  • 90