Method of editing json configuration file in. net core

  • 2021-12-04 09:53:29
  • OfStack

Introduction

Recently, in the development and application of specific projects, the json format configuration file is adopted in the project, and the loading of configuration file is managed by IConfiguration interface object, which is a modern configuration management tool provided by Microsoft in the era of net standard.

In the project design, it is necessary to write back the configuration information sent by the remote server to the configuration file during the running process. However, Bing or Baidu can't find a way to change configuration write-back in this modern configuration management model.

In desperation, I had to build wheels by myself.

Configuration model in NET Standard era

With the advent of the era of. NET Standard, System. Configuration no longer exists in. net core, so the Microsoft. Extensions. Configuration family configuration management class libraries are replaced:

Microsoft. Extensions. Configuration. Abstractions: Basic interface

Microsoft. Extensions. Configuration: Implement the above basic interface

Microsoft. Extensions. Configuration. FileProviderExtensions: Provides overloaded configuration extensions

Microsoft. Extensions. Configuration. Binder: Provides conversion to entity functionality

Microsoft. Extensions. Configuration. FileExtensions: Provides profile root path extension

Related article resources

With regard to the use of the above class library, there are a large number of related articles on the Internet, such as the articles of well-known blogger Ouchi Lao A, which have systematic and detailed explanations, and you can refer to them by yourself.

Link here: https://www.cnblogs.com/artech/p/config-for-net-core.html

Suggested usage of configuration classes

For programmatic convenience, instead of directly using the Configuration object created by ConfigurationBuilder to read the value of a single 1 configuration item, we tend to bind a set of related configurations into one object.

For example, the configuration parameter class of a project message topic of the author is as follows:


public class TopicConfig
{
        public string Project { get; set; } ="ibms";
        public string Device { get; set; } = "gateway";
        public string City { get; set; } = "wuhan";
        public string Area { get; set; } = "poly";
}

We can specify default parameters for the configuration class.

In objects that require configuration parameters, we can set configuration classes to property fields


private TopicConfig topicConfig = new TopicConfig();

When the object class is instantiated, the configuration class is automatically constructed and has default configuration parameters

In the object class that needs to use configuration, we write a method to load the configuration class and a method to save the configuration class. When the object class is constructed, we call and execute the loading configuration file.

When the configuration file exists, judge whether the corresponding configuration segment exists, and if so, bind to the corresponding configuration class, so as to realize the loading of configuration parameters (in the object class, where the configuration parameters need to be used, the parameters are directly obtained from the configuration class);

When the configuration file does not exist, the Load Configuration method calls the Save Configuration method to write back the default configuration to the configuration file.

When the configuration parameters need to be saved after dynamic updating, the configuration parameters are also updated to the configuration file by calling the Save Configuration method.

Sample json configuration file


{
    "topic": {
        "Project": "ibms",
        "Device": "gateway",
        "City": "wuhan",
        "Area": "poly"
    }
}

Load configuration method

The author uses the file "appsettings. json" under the program directory as the configuration file


private void LoadConfig()
        {
            var path = Directory.GetCurrentDirectory();
            var config_file = "appsettings.json";
            var full_path = Path.Combine(path, config_file);
            if (File.Exists(full_path))
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(path)
                    .AddJsonFile("appsettings.json");

                IConfiguration Configuration = builder.Build();

                if (Configuration.GetSection(Topic).Exists())//Topic Is a string constant, corresponding to the configuration segment property name 
                    Configuration.GetSection(Topic).Bind(topicConfig);// Binding configuration data to configuration classes 
            }
            else
            {
                SaveConfig();
            }
     }

In dotnet core, because of the more modular design method, the corresponding package needs to be referenced when using configuration class. We use json configuration in the program, and need to install Microsoft. Extensions. Configuration. Json package.

The Bind method is an extension method that requires the Microsoft. Extensions. Configuration. Binder package to be installed in the project first.

Packages can be installed through Nuget Package Manager.

Save configuration method


private void SaveConfig(string path = "")
{
        if (path == "") path = Directory.GetCurrentDirectory();
        Dictionary<string, object> sectionsInfo = new Dictionary<string, object>();

        sectionsInfo.Add(Topic, topicConfig); //Topic Is a string constant, corresponding to the configuration segment property name 
        JsonConfigHelper.SaveJson(sectionsInfo, path);
}

Call the json configuration save class to save the configuration to the specified location.

General Json Configuration Saving Class

To meet the need of rewriting configuration files, the author implements a general class for saving configuration files in json format, and supports saving multiple configuration classes at the same time.

Supports overwriting of existing configuration file nodes and appending configuration nodes.


using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace flyfire.Common
{
    public class JsonConfigHelper
    {
        public static bool SaveJson(Dictionary<string,object> sectionInfo, string configFilePath, string configFileName = "appsettings.json")
        {
            if (sectionInfo.Count==0)
                return false;

            try
            {
                var filePath = Path.Combine(configFilePath, configFileName);
                JObject jsonObject;

                if (File.Exists(filePath))
                {
                    using (StreamReader file = new StreamReader(filePath))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            jsonObject = (JObject)JToken.ReadFrom(reader);
                        }
                    }
                }
                else
                {
                    jsonObject = new JObject();
                }

                foreach (var key in sectionInfo.Keys)
                {
                    jsonObject[key] = JObject.FromObject(sectionInfo[key]);
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer)
                {
                    Formatting = Formatting.Indented,// Format Indent 
                    Indentation = 4,  // Indent 4 Characters 
                    IndentChar = ' '  // Indented characters are spaces 
                })
                {
                    jsonObject.WriteTo(jsonwriter);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

At this point, we have completed the loading, binding and saving of Json format configuration file.

These are the details of editing the json configuration file in net core. For more information about the net core json configuration file, please pay attention to other related articles on this site!


Related articles: