5

My project is simple WebApi server, based on netcoreapp2.0.

I have simple appsettings.json

{
  "logPath":"C:\logs\myLog.log"
}

And it's logPath ok, if app will work on Windows platform, but i want also run it on linux. I know, that i can use console args or enviroment variables for override this setting, but i want to get OS specific override for appsettings.json. Something like appsettings.linux.json (may be appsettings file, that depends on RID) with content

{
  "logPath":"\var\tmp\myLog.log"
}

Ideally if this theoretical appsettings.linux.json will only included in build output, if i will build my app for specific RID.

How can i do that if it available?

Frank59
  • 3,141
  • 4
  • 31
  • 53

2 Answers2

4

You can create multiple appsettings files.

appsettings.windows.json
appsettings.linux.json

then use an EnvironmentName variable to swap between them.

Startup

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

the default appsettings.json file is loaded first if there is an {env.EnvironmentName} set then it will load that one. I use this for swapping between Dev, test and production environments.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • 2
    Thanks for answer. Yes, it's working solution. Already implemented it. Interesting to know other possible solutions for this problem. I thinked may be exists some solutions using msbuild and RID identifiers. – Frank59 Dec 07 '17 at 12:59
  • I agree it could probably be doine with MSBuild as well. – Linda Lawton - DaImTo Dec 07 '17 at 13:07
  • I had no idea that you could do this, this is ace! – Jamie Taylor Dec 07 '17 at 21:40
  • where will this env.EnvironmentName be set? – Sana Ahmed Jun 30 '22 at 06:43
  • @Sana that depends on your system. If your running this in a docker container then it would be set in there. If you are running this in say an IDE as development then you would set it up there. Im pritty sure Visual studio default sets. ASPNETCORE_ENVIRONMENT to Development. I know JetBrains Rider does. – Linda Lawton - DaImTo Jun 30 '22 at 10:30
0

Add appsettings.linux.json containing variables that need to be overwritten for this OS:

{
    "logPath":"\var\tmp\myLog.log"
}

In Program.cs before calling config.Build() run:

if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    config.AddJsonFile("appsettings.linux.json");
}
Silv
  • 673
  • 5
  • 19