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 5 Aug 2021, 15:46 PM
Tags: c#,.net core,.net 5.0,Web