Reputation: 127
I have custom appsettings.json files for each environment, so appsettings.Dev.json, appsettings.Test.json, appsettings.Prod.json. In the main appsettings.json, I have the following code:
"EmailSettings": {
"Recipients": [
"[email protected]"
]
}
Then in the custom json file, I want to override this list, like this:
"EmailSettings": {
"Recipients": [
"[email protected]"
]
}
But instead, this gets appended like this:
"EmailSettings": {
"Recipients": [
"[email protected]",
"[email protected]"
]
}
With all other types of settings, they get replaced, but for some reason, it seems that lists in custom settings files get appended instead. With .net, you used to have more granularity with the xslt to be able to determine whether you wanted to replace or append overridden settings. Any suggestions here?
I did this, and it gets replaced in the custom json settings. Main appsettings.json:
"EmailSettings": {
"Recipients:0": "[email protected]"
}
Then in the custom settings file:
"EmailSettings": {
"Recipients:0": "[email protected]"
}
Thanks for the responses!
Upvotes: 5
Views: 2142
Reputation: 4355
I utilized different appsettings
files for environments (including Development
)
So first make sure you have added the environment json file in your configuration:
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true, reloadOnChange: true)
Then in my original appsettings.json
it would be something like:
"EmailSettings": {
"Recipients": []
}
and then for local development (Development
environment): appsettings.Development.json
"EmailSettings": {
"Recipients": [
"[email protected]"
]
}
and then for the other environment (lets call it Staging
): appsettings.Staging.json
"EmailSettings": {
"Recipients": [
"[email protected]"
]
}
Then, just make sure in your additional environments you have set ASPNETCORE_ENVIRONMENT
in environment variables.
Upvotes: 1
Reputation: 9918
In the appsettings.Test.json
use the following
"EmailSettings:Recipients:0" : "[email protected]"
The Configuration API is capable of maintaining hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.
You will need to define the Email Settings class like
public class EmailSettings
{
public List<string> Recipients { get; set; }
}
and wireup the DI to add the options in the Configure
Method in Startup
class
public void ConfigureServices(IServiceCollection services)
{
// add Options
services.AddOptions();
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Upvotes: 0