Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

Microsoft.Configuration.Extensions: How to get section / complex value as json string?

When we have configuration like this

// appsettings.json
{
    "SomeServiceConfiguration": {
       "Server": "127.0.0.1",
       "Port": "25"
    }
}

it is possible to use binding to access data:

IConfiguration configuration =  ...;
var section = configuration.GetSection("SomeServiceConfiguration");
var val = section.Value; // this is null
var t = new SomeServiceConfiguration();
section.Bind(t);

But is it possible to get value (section content) "just as string" (by the fact as json) {"Server": "127.0.0.1", "Port": "25"} ?

Upvotes: 1

Views: 943

Answers (1)

janniks
janniks

Reputation: 3180

According to ConfigurationSection Class this is not directly possible.

However, you could serialize to XML using the ConfigurationElement.SerializeElement(XmlWriter, Boolean) Method, which is possible by default. You would have to convert to JSON afterwards, so this seems overkill.

I would recommend building a new JSON Object and accessing the section values directly.

Upvotes: 1

Related Questions