AppSettings.json in .Net Core Console

Getting access to the app setting from a .Net Core console app.

Getting access to the settings in the appsettings.json from a Web App or API in .Net Core is straight forward as it built into the template. When you want to add it to a .Net Core Console App you need to do some setup

Create a new appsettings.json file in the root of your project. The properties for ‘Copy to Output Directory’ for the file should be set to ‘Copy if newer’. This will ensure the file is part of the output files.

Add the following NuGet packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Configuration.ConfigurationBinder

Code

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleTemplate
{
	class Program
	{
		static void Main(string[] args)
		{
			var builder = new ConfigurationBuilder()
			.SetBasePath(Directory.GetCurrentDirectory())
			.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
		
			IConfigurationRoot configuration = builder.Build();

			var greeting = configuration.GetValue(typeof(String), "AppSettings:Greeting").ToString();

			var myConnectString = configuration.GetConnectionString("MyConnectionString");

			Console.WriteLine(greeting);
			Console.WriteLine(myConnectString);
			Console.Read();

		}
	}
}

AppSettings.json

{
	"ConnectionStrings": {
		"MyConnectionString": "The connection to the database"
	},
	"AppSettings": {
		"Greeting": "Hello world"
	}
}

If you try to run the following in Azure and expect the Environment Variables that you set within App Service-> Configuration, to be substituted in then unfortunately they won’t. You will need to make the following additions to your code to ensure the environmental values are substituted for your application setting and connection strings.

Add the following NuGet package:

  • Microsoft.Extensions.Configuration.EnvironmentVariables

Add ‘.AddEnvironmentVariables()’ into your ConfigurationBuilder setup:

	var builder = new ConfigurationBuilder()
		.SetBasePath(Directory.GetCurrentDirectory())
		.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
		.AddEnvironmentVariables();
Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me