ASP.NET Core Configuration GetSection.Get returns null

If you find yourself populating the configuration object of .NET Core using the GetSection.Get method and all of your properties have been set to null or the default value, then this quick tip may save your hours.

At first I thought that it may be down to the class object having come complicated variables or including methods, or perhaps that the types of the appconfig.json file don't match up with those of the specified class, but it turns out that you actually just need to add { get; set;} to each of the properties and it will fill them on the next application start like nothing ever happened, see the code below:

public class MyConfig
{ public string MyConfigProperty1 { get; set;} // This works public string MyConfigProperty2; // This does NOT work }

Once that's done, you can access it one of two ways, inject it into your controllers, views and services, or use a static reference, the below code will allow both to be used:

// Add our Config object so it can be injected
colServices.Configure(_configuration.GetSection("MySection"));

// Keep a static reference to it so we can always access it easily.
objConfiguration = _configuration.GetSection("MySection").Get();

Just add them into the 'public void ConfigureServices(IServiceCollection colServices)' section of Startup.cs and you're good to go.

You might also find this post on stack overflow useful as it has a lot of great answers:
https://stackoverflow.com/questions/43973265/asp-net-core-json-configuration-getsection-returns-null
Some text


Published at

Tags: c#,.net core,.net 5.0,Web

Luke Alderton

Comments

Share with
Tags
Latest Comments
By Mark Gentry on Windows Server 2019 - Change product key does nothing
20 Aug 2021, 03:30 AM
By Cathy on In-Place Upgrade for a Windows Server domain controller
31 Jul 2021, 18:28 PM
By Mr. Greymatter on Raspberry Pi - Running Java app on Raspbian
16 Feb 2021, 07:35 AM
By Mikko Seittenranta on Xamarin Forms multiple instances of same app open
16 Feb 2021, 04:34 AM
By Andrew on Auto/Custom height on Xamarin Forms WebView for Android and iOS
22 Jan 2021, 22:15 PM
By Nick on Raspberry Pi - Running Java app on Raspbian
14 Oct 2020, 19:37 PM
By Ivan on Fixed: Value cannot be null Parameter Name: source
15 Sep 2020, 19:47 PM
By Anand on Raspberry Pi - Bluetooth using Bluecove on Raspbian
7 Sep 2020, 16:53 PM
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development