Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override ASP.NET Core configuration array settings using environment variables

TL;DR

In an ASP.NET Core app, I have an appsettings.json config file which uses a JSON array to configure a collection of settings.

How do I override a setting of one of the array objects using environment variables?

Background

I'm using Serilog in an ASP.NET Core application and using the Serilog.Settings.Configuration, to allow it to be configured using appsettings.json.

The configuration is like this:

{   "Serilog": {     "Using":  ["Serilog.Sinks.Literate"],     "MinimumLevel": "Debug",     "WriteTo": [       { "Name": "File", "Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" } }     ],     "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],     "Properties": {         "Application": "Sample"     }   } } 

When deployed, I want to override some of the settings, e.g. the MinimumLevel, and the path to the log file. My preferred option is to do this via environment variables as I'm deploying to an Azure App Service, so I'll use the App settings through the Azure management portal (these are realised as environment variables).

I can easily set the MinimumLevel by adding an environment variable with the name: Serilog:MinimumLevel and the application name Serilog:Properties:Application.

What is the format for specifying a setting with an array?

like image 646
James Skimming Avatar asked Jun 06 '16 12:06

James Skimming


People also ask

Where is Aspnetcore_environment environment variable?

In Visual Studio, we can set ASPNETCORE_ENVIRONMENT in the debug tab of project properties. Open project properties by right clicking on the project in the solution explorer and select Properties. This will open properties page. Click on Debug tab and you will see Environment Variables as shown below.

What is IConfiguration in ASP.NET Core?

The IConfiguration is an interface for . Net Core 2.0. The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IConfiguration interface is used to read Settings and Connection Strings from AppSettings. json file.


1 Answers

After looking at the configuration in the debugger I found the answer.

  • Serilog__WriteTo__0__Args__path (All platforms)
  • Serilog:WriteTo:0:Args:path (Windows)
  • Serilog--WriteTo--0--Args--path (sourced From Azure Key Vault)

Note: The Configuration in ASP.NET Core documentation now covers this.

So I need to use the array index (zero-based) as if it were a name.

Here is the screenshot of the debugger, also (thanks to Victor Hurdugaci in the comments), the unit tests are a good place to look for examples.

configuration in the debugger

like image 195
James Skimming Avatar answered Oct 03 '22 09:10

James Skimming