Friday, 16 April 2021

Config File in .Net Core

To add a configuration file in a .NET Core project, first add a new file JavaScript JSON Configuration File.

Set the file properties; Copy to Output Directory: 'Copy if newer' or 'Copy always'.

Say we put this inside the file:
{
  "ApplicationKey": "a_secret_value",
  "ConnectionStrings": {
    "StudentBoundedContextConnectionString": "server=Server_Name;database=DB_Name;trusted_connection=true",
    "CourseBoundedContextConnectionString": "server=Server_Name;database=DB_Name;trusted_connection=true"
  } 
}

On Package Manager, add Microsoft.Extensions.Configuration.Json.

Then to read the values on our codes:
var config = new ConfigurationBuilder()
				 .AddJsonFile("your_filename.json")
				 .Build();

var appkey = config["ApplicationKey"];
var studentConnectionString = config["ConnectionStrings:StudentBoundedContextConnectionString"];

No comments: