.Net Core application JSON file configuration technique has come into picture by replacing traditional way like Web.Config file approach. By default application loads "appSettings.json" file on startup. If we have defined environment variable then application also loads environmental specific json files like "appSettings.Development.json"(for environment variable is Development), "appSettings.Stage.json"(for environment variable is Stage), "appSettings.Production.json"(for environment variable is Production) along with the "appSetting.json".
Create A Sample .Net Core Application:
Now for better understanding let's walk through with a sample .Net Core Web API application. The application can be created either by using Visual Studio 2019(VS Editor supports .Net Core Version 3.0plus) or visual Studio Code
App Loads appSettings.json And appSettings.{Environmental_Variable}.json By Default:
On application start, appSettings.json and appSettings.{Environment_Variable}.json file automatically loaded by the application and injected those file values into the Microsoft.Extensions.Configuration.IConfiguration in Startup file. So let's add debugger in Startup.cs file and inspect the JSON files as below.
Here in the picture, we can observe that appSettings.json and appSettings.Development.json are loaded on the app starts.
Let's change the 'Environmental variable' to confirm based on setting the file will get loaded.
In Visual Studio Code editor to set the environment variable for testing open the launch.json file in '.vscode' folder as below
For Visual Studio 2019 or 2017 open launchSettings.json file in 'Properties' folder.
Now let change the environmental variable to 'Stage' and check the Startup.cs file by running application in debug mode as below.
Values Of appSettings.json Override By appSetting.{Environmental_Variable}.json:
Till now we learnt along with appSetting.json file environmental variable json files get loaded on application starts. One more important thing to remember is appsettings.json file values will be overridden by appsettings.{environmental_variable}.json while reading the settings in the application. So properties name should be matched in both files to get the benefit of the override mechanism.
Let's understand this overriding concept by implementing a sample endpoint. Now in "appsetting.json" file add new object property as below
appsettings.json:
{ "MyUser":{ "VariableName":"Production" } }Let's add a model to represent the above JSON object
Model/MyUser.cs:
public class MyUser { public string VariableName{get;set;} }Now register 'MyUser' object with the json object in Startup.cs as below
Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.Configure<Models.MyUser>(Configuration.GetSection("MyUser")); }Now let's create a testing endpoint as below.
Controllers/TestController.cs:
[Route("test")] public class TestController : ControllerBase { private readonly MyUser _myUser; public TestController(IOptions<MyUser> myUser) { _myUser = myUser.Value; } [Route("get")] public IActionResult Get() { return Ok(_myUser); } }#L5 at this line number 'MyUser' object gets injected into the constructor using 'Microsoft.Extension.Options.IOption<MyUser>
Now run the application and output shows as below.
Now override the appsettings.json values with the appsettings.Development.json file values
appsettings.Development.json:
{ "MyUser":{ "VariableName":"Development" } }Now re-run the application and output shows like appsettings.Development.json values override the appsettings.json values as below.
Load Custom JSON File:
Configuring everything into the appsettings.json file is good, but there are cases where a large number of settings need to be read from a file(which are not suitable to store in Database) in that case adding everything into the appsettings.json makes the file more tedious and confusing. So it is always best to practise to maintain separate JSON files in this kind of scenarios. After separating settings into the custom file we need to configure the custom file to load at the time of application starts just like the appsettings.json.
Let's add a sample JSON file like 'myCustom.json' at the location(the root of the application) where appsettings.json existed.
Now in Program.cs file we need to use an extension method of IHostBuilder like 'ConfigureAppConfiguration' method. This method helps to add n-number of custom JSON files which gets loaded on application starts.
Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hoistingContext, config) => { config.AddJsonFile("myCustom.json"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });#L4 at this we are adding our custom JSON file inside of the 'ConfigureAppConfiguration' methods. So this file will get loaded automatically along with appsettings.json file.
Now run the application in debug mode and we can see 'myCustom.json' file loaded.
Load Custom JSON File Based On Environmental Variable:
We can load custom files based on environment variable configured for the application.
Let's add files with environment variable inside of their file name as below.
Now update the "ConfigureAppConfiguration" method in Program.cs file as below.
Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hoistingContext, config) => { config.AddJsonFile($"myCustom.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });#L4 at this line using 'System.Environment.GetEnvironmentVariable()' method is used to fetch variable value.
Now run the application in debug mode and output as shown below.
Load JSON File From Custom Path:
Previously we have created custom JSON file in the root path, so we simply specified file name in Program.cs. If we have more number of custom JSON file it is good to maintain them inside of the folders.
Let's add our custom JSON file inside of the 'wwwroot' folder as below.
Update the Program.cs file as below.
Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hoistingContext, config) => { config.AddJsonFile("wwwroot/Config/myCustom.json"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });#L4 at this line JSON file configured with the full file path.
Now run the application in debug mode and output shown below.
Wrapping Up:
Hopefully, I think this article delivered some useful information about loading of appsetting.json and custom JSON files in .Net Core application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment