引言

最近在具体项目开发应用中,项目采用的json格式配置文件,配置文件的加载采用的iconfiguration接口对象进行的管理,这是.net standard时代,微软所提供的现代化的配置管理工具。

项目设计中,需要在运行过程中,将远程服务端发送过来的配置信息回写到配置文件中。然而,必应也好,百度也罢,翻遍网络,这套现代化的配置管理模型中,却找不到一个可以改变配置回写的方法。

无奈之下,只好自己动手,手动造轮子了。

.net standard时代的配置模型

随着.net standard时代的来临,system.configuration在.net core中已经不存在了,那么取而代之的是microsoft.extensions.configuration系列配置管理类库:

microsoft.extensions.configuration.abstractions:基础接口

microsoft.extensions.configuration:实现上面的基础接口

microsoft.extensions.configuration.fileproviderextensions:提供重载配置扩展

microsoft.extensions.configuration.binder:提供转换到实体功能

microsoft.extensions.configuration.fileextensions:提供配置文件根路径扩展

相关文章资源

关于以上类库的使用,网上有大量相关文章,如知名博主大内老a的文章中,有着系统、详细阐述,各位可自行查阅。

链接在此:https://www.cnblogs.com/artech/p/config-for-net-core.html

配置类的建议用法

出于编程上的便利,我们通常不会直接利用configurationbuilder创建的configuration对象读取某个单一配置项的值,而是倾向于将一组相关的配置绑定为一个对象。

例如笔者某个项目消息主题配置参数类如下:

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

我们可以为配置类指定默认参数。

在需要使用配置参数的对象中,我们可以将配置类设置为属性字段

private topicconfig topicconfig = new topicconfig();

当对象类被实例化时,配置类将自动被构造并拥有默认配置参数

我们在需要使用配置的对象类中,写一个加载配置类的方法和保存配置类的方法,当对象类构造时,调用并执行加载配置文件。

当配置文件存在时,判断对应的配置段是否存在,如果存在,则绑定到对应的配置类,从而实现配置参数的加载(对象类中,相关需要使用配置参数的地方,直接从配置类的获取参数);

当配置文件不存在时,加载配置方法调用保存配置方法,将默认配置回写到配置文件中。

当配置参数动态更新后需要保存时,也通过调用保存配置方法,将配置参数更新到配置文件中。

示例json配置文件

{
    "topic": {
        "project": "ibms",
        "device": "gateway",
        "city": "wuhan",
        "area": "poly"
    }
}

加载配置方法

笔者采用程序目录下的”appsettings.json”文件作为配置文件

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为字符串常量,对应配置段属性名称
                    configuration.getsection(topic).bind(topicconfig);//绑定配置数据到配置类
            }
            else
            {
                saveconfig();
            }
     }

在dotnet core由于采用了更为模块化的设计方式,使用配置类需要引用相应的程序包,我们在程序中使用json配置,需要安装microsoft.extensions.configuration.json程序包。

bind方法为扩展方法,需要项目中先安装microsoft.extensions.configuration.binder程序包。

程序包可通过nuget包管理器进行安装。

保存配置方法

private void saveconfig(string path = "")
{
        if (path == "") path = directory.getcurrentdirectory();
        dictionary<string, object> sectionsinfo = new dictionary<string, object>();

        sectionsinfo.add(topic, topicconfig); //topic为字符串常量,对应配置段属性名称
        jsonconfighelper.savejson(sectionsinfo, path);
}

调用json配置保存类,将配置保存到指定的位置。

通用json配置保存类

笔者针对需要改写配置文件的应用的需要,自行实现了一个保存json格式配置文件的通用类,支持同时保存多个配置类。

支持对现有配置文件节点的改写和追加配置节点。

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,//格式化缩进
                    indentation = 4,  //缩进四个字符
                    indentchar = ' '  //缩进的字符是空格
                })
                {
                    jsonobject.writeto(jsonwriter);
                    return true;
                }
            }
            catch (exception)
            {
                return false;
            }
        }
    }
}

至此,我们完成了json格式配置文件的加载、绑定与保存。

以上就是.net core中编辑json配置文件的详细内容,更多关于.net core json配置文件的资料请关注www.887551.com其它相关文章!