Adding AppSettings.json Configuration to a .NET Core Console Application

This post will walk you through the steps necessary to add a strongly typed appsettings.json configuration file to your console application. I’ll dispense with the formalities of writing a detailed introduction on why you would be interested in doing this and jump right into the steps involved.

Note: This post assumes .NET Core 2.1, but I believe any 2.x version will work.

1. Add the following NuGet packages to your console application:

2. Right-click your console application, and select “Unload project“. Once the project has been unloaded, right click the project and select “Edit <your_console_project_name>.csproj“.

3. Add the following just below the <TargetFramework> element:
<UserSecretsId>93d033dc-12eb-446a-91a6-efec88dfb437</UserSecretsId>
(note: you should replace this guid with your own)

4. Add the following to a <ItemGroup> with other CliToolReference elements, or add your own:

5. Right-click your console application and select the “Reload project” option.

6. Open the developer command prompt and navigate to the directory with your console application, then run:

Note: This will create a secrets.json file located at: %APPDATA%\Microsoft\UserSecrets\<SecretId_From_Step_3>\secrets.json
Edit the newly created file and change the contents to:

7. Create a new JSON configuration file for your console application and name it appsettings.json. Set the following to the contents of the file to the JSON below. Important: Be sure to right-click this file and select properties. Change the “Copy to Output Directory” option to “Copy if newer”.

8. Create a class named MySettingsConfig:

9. Add the following code to your Main routine inside Program.cs

If your console shows your settings correctly, congratulations! If you’re missing the AccountName and ConnectionString settings, be sure you followed the step to “Copy to Output Directory” listed in step 7.

 

Kyle Ballard

Software engineer specializing in Ecommerce.