Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Variable replacements in appSettings.json to reference other config values

Imagine the following appSettings.json file:

{
   "GlobalSettings": {
        "BaseUrl": "http://example.com:5000"
    },
    "NavigationSettings": {
        "LoginUrl": "{GlobalSettings:BaseUrl}/Login"
    }
}

What I'd like to do is to automatically replace the value of GlobalSettings:BaseUrl within the value of NavigationSettings:LoginUrl. I know one can use appSettings.{env}.json to override specific keys, but that overrides the entire value, not just part of it.

I could work around this by using an extension method something like the following, but this would require the programmer to remember to call the extension method everywhere they might want to have a config value replaced.

ReplaceConfigValues(this string input, IConfiguration config) { /*...*/ }

Can anyone suggest any alternative methods I could use, or are there some new .Net Core features I might be missing?

Even something like referencing a environment variable within the config value would be useful, but I don't know of a way to do that either. E.g.

"LoginUrl": "${ENV_GLOBAL_BASE_URL}/Login"
like image 340
91dave Avatar asked Jul 18 '17 17:07

91dave


1 Answers

The comment from Tseng is true, there is nothing built-in yet. I created a library for that purpose it does exactly what you expect. See: https://github.com/molinch/ConfigurationSubstitutor You just need to register it as another configuration source.

For example if you have these three entries defined in the configuration:

  • Foo = {Bar1}{Bar2}{Bar1}
  • Bar1 = Barista
  • Bar2 = -Jean-

When requesting Foo from the configuration you will get: Barista-Jean-Barista

like image 149
Fabien Avatar answered Oct 13 '22 00:10

Fabien