Matthias
Matthias

Reputation: 1436

IConfiguration Save in vNext (Microsoft.Framework.ConfigurationModel in Asp.Net Mvc 6.0.0-beta4)

We are using

private Configuration _configuration = new Configuration();

Then load some parameters from the file with e.g.:

 SomeConfig= _configuration.Get<string>("SomeConfig");

Then we also Set does variables again e.g. changed by User Interface with:

_configuration.Set<string>("SomeConfig", SomeConfig);

I thought that there must be a way to serialise it back to the original JSON file we loaded from:

We are using this:

_configuration.AddJsonFile("our-config.json");

It seems to change only the in memory representation but does not save the file back to JSON. So I am wondering why I should use this configuration infrastructure when it does not support me serialising my configs again? Maybe it should be only used for things which were earlier in web.config? Could you give me some details about why there is no Save method and why I should not just implement a JSON serialise and deserialise class?

Update: The use case for this configuration file is: It should be used to store the connection strings to a database. The web application should show a setup page allowing the administrator installing the web application and define those parameters in a setup page. That is why I want to change it in code.

Upvotes: 1

Views: 185

Answers (1)

Matthias
Matthias

Reputation: 1436

It seems that is not possible to do this. The new configuration model does only support the reading of the files. I used JSON newtonsoft in order to do the serialisation back to the file:

//Initialise newtonsoft classes (Indented for pretty print)
JsonSerializerSettings jsonSettigns = new JsonSerializerSettings();
jsonSettigns.Formatting = Formatting.Indented;
JsonSerializer jsonSerializer = JsonSerializer.Create(jsonSettigns);

//Open normal text writer and give Serialize function the handle
TextWriter textWriter = File.CreateText(FullConfigFilePath);
jsonSerializer.Serialize(textWriter, document);

textWriter.Close();

In order to get the configuration path for the file saving I am using this code:

foreach (IConfigurationSource source in _configuration.Sources) {
    if(source is JsonConfigurationSource) {
        jsonSource = (JsonConfigurationSource)source;
        FullConfigFilePath = jsonSource.Path;
    }
}

This seems not to be the optimal solution. I think I probably should not use the configuration model at all for this scenario, or I should probably extend the Configuration class.

Upvotes: 2

Related Questions