asp.net core 系列 11 配置configuration (下)

四. 文件配置提供程序AddIniFile、 AddXmlFile、AddJsonFile

  FileConfigurationProvider 是从文件系统加载配置的基类。 以下配置提供程序专用于特定文件类型:

    (1) INI 配置提供程序 IniConfigurationProvider: FileConfigurationProvider

    (2) JSON 配置提供程序 JsonConfigurationProvider: FileConfigurationProvider

    (3) XML 配置提供程序 XmlConfigurationProvider: FileConfigurationProvider

 

  4.1  INI 配置提供程序

    IniConfigurationProvider 在运行时从 INI 文件键值对加载配置,若要激活 INI 文件配置,请在 ConfigurationBuilder 的实例上调用 AddIniFile 扩展方法。冒号可用作 INI 文件配置中的节分隔符。下面是一个ini配置文件通用示例:

    [section0]
    key0=value
    key1=value

    [section1]
    subsection:key=value

    [section2:subsection0]
    key=value

    [section2:subsection1]
    key=value
//下面是获取各节点中的value值,需要加载的键。
    section0:key0
    section0:key1
    section1:subsection:key
    section2:subsection0:key
    section2:subsection1:key

    下面示例是使用config.AddIniFile方法加载一个config.ini文件,该方法重载允许指定:(1) optional文件是否可选,(2)reloadOnChange如果文件更改,是否重载配置。IFileProvider只读该文件。

    config.SetBasePath(Directory.GetCurrentDirectory());
    config.AddIniFile("config.ini", optional: true, reloadOnChange: true);
    //OtherPages/Page1页面访问,val 值value
     string val=  Configuration.GetSection("section0").GetSection("key0").Value;

 

  4.2 JSON 配置提供程序

    JsonConfigurationProvider 在运行时期间从 JSON 文件键值对加载配置。若要激活 JSON 文件配置,请在 ConfigurationBuilder 的实例上调用 AddJsonFile 扩展方法。下面是使用config. AddJsonFile方法加载一个config.json文件,具体格式可参考appsettings.json

      config.SetBasePath(Directory.GetCurrentDirectory());
      config.AddJsonFile("config.json", optional: true, reloadOnChange: true);

    效果就不再具体演示,重点讲下注意事项:使用 CreateDefaultBuilder 初始化新的 WebHostBuilder 时,会自动调用 AddJsonFile 两次。 调用该方法来从以下文件加载配置:(1)appsettings.json – 首先读取此文件。(2) appsettings.{Environment}.json。也就是说调用二次AddJsonFile后,AddJsonFile才会调用上面显示指定的config.json.

 

  4.3 XML 配置提供程序

    XmlConfigurationProvider 在运行时从 XML 文件键值对加载配置。若要激活 XML 文件配置,请在 ConfigurationBuilder 的实例上调用 AddXmlFile 扩展方法。XML文件创建配置键值对时,将忽略配置文件的根节点。 不要在文件中指定文档类型定义 (DTD) 或命名空间。

    config.SetBasePath(Directory.GetCurrentDirectory());
    config.AddXmlFile("config.xml", optional: true, reloadOnChange: true);

    (1)下面是一个xml配置文件通用示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <section0>
        <key0>value</key0>
        <key1>value</key1>
      </section0>
      <section1>
        <key0>value</key0>
        <key1>value</key1>
      </section1>
    </configuration>
//下面是获取各节点中的value值,需要加载的键。 section0:key0 section0:key1 section1:key0 section1:key1

    (2) 如果使用 name 属性来区分元素,则使用相同元素名称的重复元素可以正常工作:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <section name="section0">
        <key name="key0">value</key>
        <key name="key1">value</key>
      </section>
      <section name="section1">
        <key name="key0">value</key>
        <key name="key1">value</key>
      </section>
    </configuration>

    //下面是获取各节点中的value值,需要加载的键。
    section:section0:key:key0
    section:section0:key:key1
    section:section1:key:key0
    section:section1:key:key1

    (3) 属性可用于提供值

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <key attribute="value" />
      <section>
        <key attribute="value" />
      </section>
    </configuration>

    //下面是获取各属性中的value值,需要加载的键。
    key:attribute
    section:key:attribute

 

五. Key-per-file 配置提供程序 AddKeyPerFile

  KeyPerFileConfigurationProvider 使用目录的文件作为配置键值对。 该键是文件名。 该值包含文件的内容。 Key-per-file 配置提供程序用于 Docker 托管方案。若要激活 Key-per-file 配置,请在 ConfigurationBuilder 的实例上调用 AddKeyPerFile 扩展方法。 文件的 directoryPath 必须是绝对路径。

  下面示例是使用config.AddKeyPerFile方法加载一个目录文件,在使用Docker 托管时具体参考官方文档。

       config.SetBasePath(Directory.GetCurrentDirectory());
       var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");
        config.AddKeyPerFile(directoryPath: path, optional: true);

 

 六. 内存配置提供程序AddInMemoryCollection

   MemoryConfigurationProvider 使用内存中集合作为配置键值对。若要激活内存中集合配置,请在 ConfigurationBuilder 的实例上调用 AddInMemoryCollection 扩展方法。

       /// <summary>
        /// 构建内存对象的键值对
        /// </summary>
        public static readonly Dictionary<string, string> _dict =
         new Dictionary<string, string>
        {
            {"MemoryCollectionKey1", "value1"},
            {"MemoryCollectionKey2", "value2"}
        };

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
       .ConfigureAppConfiguration((hostingContext, config) =>
       {
           config.AddInMemoryCollection(_dict);
       })
       .UseStartup<Startup>();
    //OtherPages/Page1页面访问,val 值value
    string val=Configuration.GetSection("MemoryCollectionKey1").Value

 

七. 读取GetValue、GetSection、GetChildren 和 Exists

  7.1 GetValue

     ConfigurationBinder.GetValue<T> 从具有指定键的配置中提取一个值,并将其转换为指定类型。 如果未找到该键,则重载允许你提供默认值。以下示例使用键 NumberKey 从配置中提取字符串值,键入该值作为 int,并将值存储在变量 intValue 中。 如果在配置键中找不到 NumberKey,则 intValue 会接收 99 的默认值。

    var intValue = config.GetValue<int>("NumberKey", 99);

  7.2 GetSection

    IConfiguration.GetSection 使用指定的子节键提取配置子节。GetSection 永远不会返回 null。 如果找不到匹配的节,则返回空 IConfigurationSection。

 { 
  "section0": {
    "key0": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  },
  "section2": {
    "subsection0" : {
      "key0": "value",
      "key1": "value"
    },
    "subsection1" : {
      "key0": "value",
      "key1": "value"
    }
  }
}
    //返回仅包含 section1 中键值对的 IConfigurationSection 对象
    var configSection = _config.GetSection("section1");

    //获取 section2:subsection0 中键的值
    var configSection = _config.GetSection("section2:subsection0");

  7.3 GetChildren

    //在上面的json结构中,获取section2下面的子节点
    var configSection = _config.GetSection("section2");

    var children = configSection.GetChildren();

  7.4 Exists

  //在上面的json结构中,确定配置节是否存在, 为false,是因为配置数据中没有 section2:subsection2 节点
  var sectionExists = _config.GetSection("section2:subsection2").Exists();

 

八. 绑定到类

   使用GetSection方法调用 Bind 可以构造 POCO 对象。POCO就是简单CLR对象(Plain Old CLR Object),这种类不继承于任何对象(或者说直接继承于Object),示例应用包含 Starship 模型 (Models/Starship.cs)。

     config.SetBasePath(Directory.GetCurrentDirectory());
     config.AddJsonFile("starship.json",false,true);

  Starship实体对应JSON的 starship 节点

  {
    "starship": {
      "name": "USS Enterprise",
      "registry": "NCC-1701",
      "class": "Constitution",
      "length": 304.8,
      "commissioned": false
    },
    "trademark": "Paramount Pictures Corp. http://www.paramount.com"
  }
   // OtherPages/Page1页面绑定starship 节点到Starship实体中
       var starship = new Models.Starship();
       Configuration.GetSection("starship").Bind(starship);

 

  总结:

    Configuration配置的其它知识点如:将数组绑定至类、自定义配置提供程序、在启动期间访问配置、在 Razor Pages 页或 MVC 视图中访问配置等等, 请参考官方文档。

    在Configuration配置的上下二篇中,讲到了Configuration对不同配置来源的加载和读取方法,Microsoft.Extensions.Configuration.IConfiguration中全是以Get开头的只读方法,并没有涉及到对配置来源(如json或xml文件)的增删改操作。像配置的xml文件,是否需要引入System.Xml.Linq来操作xml文件的增删改操呢?带着这个疑问在以后章节再了解。

 

参考文献

官方资料:asp.net core 配置

 

posted on 2019-01-18 14:06  花阴偷移  阅读(1677)  评论(0编辑  收藏  举报

导航