1

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"} ?

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
  • I'm not quite sure what you're asking. Are you asking how do you read a particular section of the `appsettings.json` into a string? – Justin Helgerson Aug 25 '18 at 00:01
  • Yes. In case when it is complex type, not just plain string value. Help me to improove the question. – Roman Pokrovskij Aug 25 '18 at 00:07
  • Because I want to deserialize it by myself – Roman Pokrovskij Aug 25 '18 at 00:13
  • But you are already binding the object from the section, which should populate the object from the section values. – Nkosi Aug 25 '18 at 00:17
  • @RomanPokrovskij What do you mean by complex type? You can deserialize into an object which contains strings, integers, other custom objects, etc. Maybe share an example of the object you ultimately want to deserialize into? – Justin Helgerson Aug 25 '18 at 00:22
  • I do not know internal representation of section. If it is a wrapper around of json fragment - I would like to get this fragment. – Roman Pokrovskij Aug 25 '18 at 00:22
  • My sample is good enough. There is section named SomeServiceConfiguration, I can get it as 1) Section 2) Deserialized Type (through Bind method), But I would like to get it as string "{\"Server\": \"127.0.0.1\", \"Port\": \"25\"}". – Roman Pokrovskij Aug 25 '18 at 00:26
  • If you want it as a string just store the text in a file and read it. `IConfigurationProvider` isn't of much help to you here. – Justin Helgerson Aug 25 '18 at 03:41
  • @JustinHelgerson IConfigurationProvider is not used only for deserialization/binding. – Roman Pokrovskij Aug 25 '18 at 09:08

1 Answers1

1

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.

janniks
  • 2,942
  • 4
  • 23
  • 36
  • Thank you. I also think that this impossible, abstraction of section "completely hides" internal data representation. Still I will left the question open, since I do not understand was this"completeness" necessay by design and could be it changed in future? – Roman Pokrovskij Aug 29 '18 at 09:54