How to load values for different appsettings.json files from their respective properties files in .NET Core

707 Views Asked by At

I am working on a .NET Core project where I have an appsettings.json file for each environment (Dev, Prod). I want to load values for these appsettings files from the respective properties files (application.dev.properties, application.prod.properties).

I have tried using the Addpropertiesfile method like below to achieve this.

 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Configuration.JSON;

 var builder = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json")
                      .AddJsonFile($"appsettings.{environment}.json");

How can I achieve what I am trying to do?

2

There are 2 best solutions below

2
Qing Guo On

In asp.net core we have the appsettings.json, appsettings.{Environment}.json like the structure:

enter image description here

Non-prefixed environment variables are environment variables other than those prefixed by ASPNETCORE_ or DOTNET_. For example, the ASP.NET Core web application templates set "ASPNETCORE_ENVIRONMENT": "Development" in launchSettings.json

enter image description here

"profiles": {
  "emp": {
    "commandName": "Project",
    "dotnetRunMessages": true,
    "launchBrowser": true,
    "applicationUrl": "https://localhost:7271;http://localhost:5058",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  },

From Configuration in ASP.NET Core,

Using the default configuration, the EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.{Environment}.json, and user secrets. Therefore, key values read from the environment override values read from appsettings.json, appsettings.{Environment}.json, and user secrets.

To load values for different appsettings.json files, we can try to get the environment variables firstly, then loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.{Environment}.json as the below code :

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
var environment= Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ;
var config = new ConfigurationBuilder()
    .SetBasePath(pathToContentRoot)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

result: enter image description here

0
michaela112358 On

You do not need to do this directly. This is done by default in .net core. See bullet point 4 below From Microsoft documentation.

ASP.NET Core web apps created with dotnet new or Visual Studio generate the following code:

C#

var builder = WebApplication.CreateBuilder(args);

WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults. The initialized WebApplicationBuilder (builder) provides default configuration for the app in the following order, from highest to lowest priority:

  1. Command-line arguments using the Command-line configuration provider.
  2. Non-prefixed environment variables using the Non-prefixed environment variables configuration provider.
  3. User secrets when the app runs in the Development environment.
  4. appsettings.{Environment}.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  5. appsettings.json using the JSON configuration provider.
  6. A fallback to the host configuration described in the next section.

The c# code above will be placed in the Main function of the Program.cs file of a project and can automatically detect and use the correct appsettings.json file if it is named as shown.