简体   繁体   中英

How to override appsettings.json for different OS?

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?

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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM