Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure nested objects from appsettings.json in .NET Core?

VS2015 Pro, .NET Core, Web Application.

I'm trying to figure out how to get objects out of appsettings, that have nested objects. I can do it with single level objects by creating a POCO with simple types that match the config names. But with more complex objects, it's not working. I'm getting top level objects back, but they are coming back null. Here's what I have so far:

StartUp.ConfigureServices:

enter image description here

appsettings.json:

enter image description here

POCO APIContext:

enter image description here

Using Class:

enter image description here

So I get my three API objects back but they are all null. I don't know enough about the Configuration in Startup.cs to know what it's supposed to look like, but here it is.

enter image description here

like image 720
Steve Eggering Avatar asked Mar 16 '17 14:03

Steve Eggering


People also ask

Can I add more than two Appsettings json files in dotnet core?

Can I add more than two appsettings. json files in dotnet core? Of course, we can add and use multiple appsettings. json files in ASP.NET Core project.

How get values from Appsettings in NET Core?

There are two methods to retrieve our values, string dbConn = configuration. GetSection("MySettings"). GetSection("DbConnection").

How Appsettings json works in .NET Core?

The appsettings. json file is an application configuration file used to store configuration settings such as database connections strings, any application scope global variables, etc. If you open the ASP.NET Core appsettings. json file, then you see the following code by default which is created by visual studio.


1 Answers

Nested options are supported and successfully deserialized from appsettings.json. However, fields instead of properties break built-in POCO object deserialization. With the properties the problem should disappear:

public API FirstAPI { get; set; }

public string Path { get; set; }
like image 94
Ilya Chumakov Avatar answered Oct 18 '22 15:10

Ilya Chumakov