• .Net Core配置文件介绍


    Net Core中的配置文件介绍

    1 简单回顾.Net Framework配置文件

      .Net Core中的配置文件操作较.Net Framework有了很大的改动。介绍.Net Core中配置文件操作前,我们先回顾下.Net Framework中配置文件的操作。在.Net Framework中应用程序的配置文件只支持XML形式,应用程序的配置文件一般是App.Config或者Web.Config,添加配置文件最常用的方法是:在appSettings和ConnectionString节点下添加子节点,简单看一个栗子

      配置文件下添加子节点:

    <appSettings>
        <add key="mykey" value="myvalue"/>
    </appSettings>
    <connectionStrings>
        <add name="connstr" connectionString="server=.;uid=sa;pwd=xxxx;database=mydbname"/>
    </connectionStrings>

      获取配置文件中的值:

    //MVC中读取配置文件
    ViewBag.value = WebConfigurationManager.AppSettings["mykey"];
    ViewBag.connstr = WebConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
    
    //Webapi,Console,Winform应用读取配置文件
    string s1 = ConfigurationManager.AppSettings["mykey"];
    string s2 = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;

      .Net Core的配置文件相比于.Net Framework最大的特点是其不仅仅支持XML格式的配置文件,还支持Json,Ini,memory,command,env(环境变量)。首先看一个Json配置文件的栗子。

    2 Json配置文件的操作

      这里采用一个控制台项目作为栗子,Asp.NET Core中配置文件的操作基本一致。首先添加两个包

    Install-Package Microsoft.Extensions.Configuration 
    Install-Package Microsoft.Extensions.Configuration.Json 

      添加配置文件,文件名可以任意指定,这里使用appsettings.json,设置属性为【始终复制】

    {
      "isRight": true,
      "myArray": [ 10, 20, 30, 40 ],
      "myJson": {
        "key1": "json中的value1",
        "key2": "json中的value2"
      }
    }

      读取配置文件中数据,代码如下:

        class Program
        {
            static void Main(string[] args)
            {
                IConfiguration configuration = new ConfigurationBuilder()
                        //设置配置文件基本路径
                        .SetBasePath(Environment.CurrentDirectory)
                        //添加json配置。参数:optional配置文件是否为可选的,reloadOnChange是否热加载
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .Build();
                Console.WriteLine(configuration["isRight"]);
                Console.WriteLine(configuration["myArray:0"]);//输出myArray[0],     【:】表示下一级节点
                Console.WriteLine(configuration["myJson:key1"]);//输出myJson->key1   【:】表示下一级节点
                Console.ReadKey();       
            }
        }
    在.Net Core中使用ConfigurationBuilder对象的 SetBasePath(strPath) 设置配置文件的基本路径, AddJsonFile("filePath") 方法添加配置文件,Build方法创建配置对象。

    运行结果为 

    3 其他类型的配置文件

      上边提到.Net Core的配置文件支持多种类型,Configuration的数据源可以来自Json,XML,环境变量,Ini,Memory等,下边我们看一下怎么去操作其他类型配置文件。

    首先添加几个Package

    //xml配置文件
    Install-Package Microsoft.Extensions.Configuration.Xml
    //ini配置文件
    Install-Package Microsoft.Extensions.Configuration.Ini
    //环境变量
    Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables
    //支持强类型读取,扩展了IConfiguration的方法
    Install-Package Microsoft.Extensions.Configuration.Binder

    添加XML配置文件,文件名为appsettings.xml,属性设置为【始终复制】

    <appsettings>
      <mykey>myvalue</mykey>
      <mysql>
        <server>192.168.11.11</server>
        <port>3306</port>
      </mysql>
    </appsettings>

    一个简单的栗子

        class Program
        {
            static void Main(string[] args)
            {
                //memory配置数据
                var initData = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string, string>("initKey1", "初始配置数据1"),
                    new KeyValuePair<string, string>("initKey2", "初始配置数据2"),
                };
    
                IConfiguration configuration = new ConfigurationBuilder()
                        //设置根目录
                        .SetBasePath(Environment.CurrentDirectory)
                        //添加json配置。参数:optional配置文件是否为可选的,reloadOnChange是否热加载
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        //添加xml文件配置
                        .AddXmlFile("appsettings.xml")
                        //添加memory中的配置
                        .AddInMemoryCollection(initData)
                        //将环境变量添加到配置
                        .AddEnvironmentVariables()
                        .Build();
    
                //方式1:弱类型读取
                string str1 = configuration["initKey1"];
                string str2 = configuration["isRight"];
                string str3 = configuration["myArray:0"];
                string str4 = configuration["myJson:key1"];
                //我电脑上配置的NPM_HOME环境变量
                string str5 = configuration["NPM_HOME"];
                string str6 = configuration["mysql:server"];
                Console.WriteLine($"{str1}--{str2}--{str3}--{str4}--{str5}--{str6}");
    
                //方式2:强类型
                //Microsoft.Extensions.Configuration.Binder扩展了Configuration的方法
                string strA = configuration.GetValue<string>("initKey1");
                bool boolB = configuration.GetValue<bool>("isRight");
                int intC = configuration.GetValue<int>("myArray:0");
                string strD = configuration.GetValue<string>("myJson:key1");
                //我电脑上配置的NPM_HOME环境变量
                string strE = configuration.GetValue<string>("NPM_HOME");
                string strF = configuration.GetValue<string>("mysql:server");
                Console.WriteLine($"{strA}--{boolB}--{intC}--{strD}--{strE}--{strF}");
                Console.ReadKey();
            }
        }
    View Code

    运行结果

       我们看一下Configuration对象是怎么存储配置的,每一个配置源的数据都单独存放在一个Provider中,存储的方式如下图所示,无论是json/xml还是其他类型的配置源,配置最终都以Key-Value的形式存储在所对应的Provider中。

    一点重要的补充:如果多个配置文件中都配置了同一个Key值,那么以后面添加的准。如先添加XML配置文件,然后添加Json配置文件,Json配置文件会覆盖Xml配置文件中重复的配置。

    4 通过对象方式读取配置文件

      通过上边的介绍我们已经知道怎么去添加和读取配置文件,但是读取时都是用Key来获取Configuraion对象中的值,如果能以对象的形式(如:configuration.mykey形式)来读取configuration就会更方便了。 Microsoft.Extensions.Configuration.Binder 包为我们提供了这种方法。以Json配置文件为例,配置文件appsettings的内容如下:

    {
      "isRight": true,
      "myArray": [ 10, 20, 30, 40 ],
      "myJson": {
        "key1": "json中的value1",
        "key2": "json中的value2"
      }
    }

    生成configuration绑定的类,可以自己写一个绑定类。(一个小技巧:复制appsettings中的内容,【编辑】-【选择性粘贴】-【将Json粘贴为类】)

    效果如下:

    具体操作的代码如下

        class Program
        {
            static void Main(string[] args)
            {
                IConfiguration configuration = new ConfigurationBuilder()
                        //设置根目录
                        .SetBasePath(Environment.CurrentDirectory)
                        //添加json配置。参数:optional配置文件是否为可选的,reloadOnChange是否热加载
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .Build();
                
                //普通方式读取
                Console.WriteLine("----------------普通方式读取");
                Console.WriteLine($"{configuration["isRight"]}--{configuration["myArray:0"]}--{configuration["myJson:key1"]}");
    
    
                //对象方式读取
                Rootobject cfgObj = configuration.Get<Rootobject>();
                //也可以用下边的方式绑定,效果一样:
                //Rootobject cfgObj = new Rootobject();
                //configuration.Bind(cfgObj);
                Console.WriteLine("----------------对象方式读取");
                Console.WriteLine($"{cfgObj.isRight}--{cfgObj.myArray[0]}--{cfgObj.myJson.key1}");
                Console.ReadKey();
            }
        }
    
        //绑定Configuration对象的类
        public class Rootobject
        {
            public bool isRight { get; set; }
            public int[] myArray { get; set; }
            public Myjson myJson { get; set; }
        }
    
        public class Myjson
        {
            public string key1 { get; set; }
            public string key2 { get; set; }
        }

      通过对象绑定读配置文件有两个优点:①读取配置文件时为强类型读取(如configuration.isRight为bool类型,而不是统一的string类型);②具有代码提示功能

  • 相关阅读:
    快速查看表结构(zml)
    康尼机电的发送邮件的功能2
    康尼机电的发送邮件的功能1
    8.2文件控制总览只循环了第一行
    ClientScript.RegisterStartupScript
    康尼机电的委托协议中的点击操作显示标签卡的功能
    1020 Tree Traversals (25 分)
    1017 Queueing at Bank (我自己写的模拟时间的版本)
    1016 Phone Bills ( vector的使用)
    1015 Reversible Primes
  • 原文地址:https://www.cnblogs.com/wyy1234/p/10435920.html
Copyright © 2020-2023  润新知