四. 文件配置提供程序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", );

  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 配置

asp.net core 系列 11 配置configuration (下)的更多相关文章

  1. asp.net core 系列 10 配置configuration (上)

    一.  ASP.NET Core 中的配置概述 ASP.NET Core 中的应用配置是基于键值对,由configuration 程序提供. configuration  将从各种配置源提供程序操作键 ...

  2. asp.net core系列 62 CQRS架构下Equinox开源项目分析

    一.DDD分层架构介绍 本篇分析CQRS架构下的Equinox开源项目.该项目在github上star占有2.4k.便决定分析Equinox项目来学习下CQRS架构.再讲CQRS架构时,先简述下DDD ...

  3. asp.net core系列 51 Identity 授权(下)

    1.6 基于资源的授权 前面二篇中,熟悉了五种授权方式(对于上篇讲的策略授权,还有IAuthorizationPolicyProvider的自定义授权策略提供程序没有讲,后面再补充).本篇讲的授权方式 ...

  4. 【目录】asp.net core系列篇

    随笔分类 - asp.net core系列篇 asp.net core系列 68 Filter管道过滤器 摘要: 一.概述 本篇详细了解一下asp.net core filters,filter叫&q ...

  5. asp.net core 系列 16 Web主机 IWebHostBuilder

    一.概述 在asp.net core中,Host主机负责应用程序启动和生存期管理.host主机包括Web 主机(IWebHostBuilder)和通用主机(IHostBuilder).Web 主机是适 ...

  6. asp.net core 系列 14 错误处理

    一.概述 本文介绍处理 ASP.NET Core 应用中常见错误的一些方法.主要是关于:开发环境异常页:非开发环境配置自定义异常处理页:配置状态代码页(没有正文响应,http状态400~599的). ...

  7. (11)ASP.NET Core 中的配置一(Configuration)

    1.前言 ASP.NET Core在应用程序上引入Microsoft.Extensions.Configuration配置,可以支持多种方式配置,包括命令行配置.环境变量配置.文件配置.内存配置,自定 ...

  8. 技术的正宗与野路子 c#, AOP动态代理实现动态权限控制(一) 探索基于.NET下实现一句话木马之asmx篇 asp.net core 系列 9 环境(Development、Staging 、Production)

    黄衫女子的武功似乎与周芷若乃是一路,飘忽灵动,变幻无方,但举手抬足之间却是正而不邪,如说周芷若形似鬼魅,那黄衫女子便是态拟神仙. 这段描写出自<倚天屠龙记>第三十八回. “九阴神抓”本是& ...

  9. asp.net core 系列之Configuration

    在ASP.NET Core中的App configuration 是通过configuration providers基于key-value对建立的.Configuration providers读取 ...

随机推荐

  1. Python爬虫代理IP池

    目录[-] 1.问题 2.代理池设计 3.代码模块 4.安装 5.使用 6.最后 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代 ...

  2. linux系统,关于Python多版本共存

    http://www.cnblogs.com/Yiutto/p/5962906.html 给个地址直接看八~

  3. redux+saga+reducer

    saga.js这个文件里面的函数实际没有在其他jsx中引用吧?这个文件的作用就是把异步数据拿到,放进reducer,如果jsx想取,需要结合connect来取数据.

  4. 一年前的很水的渣网页(第一次html试水)

    <!doctype html> <html lang="zh-cn"> <base target="_blank" /> & ...

  5. BZOJ.4500.矩阵(差分约束 SPFA判负环 / 带权并查集)

    BZOJ 差分约束: 我是谁,差分约束是啥,这是哪 太真实了= = 插个广告:这里有差分约束详解. 记\(r_i\)为第\(i\)行整体加了多少的权值,\(c_i\)为第\(i\)列整体加了多少权值, ...

  6. C# 中传参中的OUT 和 ref 区别 笔记

    //out传参前需要对参数进行赋值处理,ref则不需要.//out.ref 传参都可以对值进行改变 1 static void Main(string[] args) { ; //int J = 10 ...

  7. ztree设置节点checked,选中某节点等相关操作

    ztree设置节点checked,选中某节点等相关操作 1.根据id获取树的某个节点: var zTree = $.fn.zTree.getZTreeObj("mytree"); ...

  8. 单点登录实现原理(SSO)

    简介 单点登录是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统的保护资源,若用户在某个应用系统中进行注销登录,所有的应用系统都不能再直接访问保护资源,像一些知名的大型网站,如:淘 ...

  9. python 用正则处理日志实例

    前提:     了解正则基本语法   import re with open('top10_xiaozhuang_net.log','r') as f1: #读取日志文件 subject=f1.rea ...

  10. android中Imageview的布局和使用

    布局: <ImageView android:id="@+id/imt_photo" android:layout_width="fill_parent" ...