1.内存配置

memoryconfigurationprovider使用内存中集合作为配置键值对。若要激活内存中集合配置,请在configurationbuilder的实例上调用addinmemorycollection扩展方法。可以使用ienumerable<keyvaluepair<string,string>> 初始化配置提供程序。构建主机时调用configureappconfiguration以指定应用程序的配置:

public class program
{
    public static readonly dictionary<string, string> _dict =
        new dictionary<string, string>
        {
            {"memorycollectionkey1", "value1"},
            {"memorycollectionkey2", "value2"}
        };
    public static void main(string[] args)
    {
        createwebhostbuilder(args).build().run();
    }
    public static iwebhostbuilder createwebhostbuilder(string[] args) =>
        webhost.createdefaultbuilder(args)
            .configureappconfiguration((hostingcontext, config) =>
            {
                config.addinmemorycollection(_dict);
            })
            .usestartup<startup>();
}

而通过启动应用程序时会看到如下配置信息:

1.1getvalue

configurationbinder.getvalue<t>从具有指定键的配置中提取一个值,并可以将其转换为指定类型。如果未找到该键,则获取配置默认值。如上述示例中,配置两个value1、value2值,现在我们在键memorycollectionkey1配置中提取对应字符串值,如果找不到配置键memorycollectionkey1,则默认使用value3配置值,示例代码如下:

public startup(iconfiguration configuration)
{
    configuration = configuration;
    var config = configuration.getvalue<string>("memorycollectionkey1", "value3");
}

而通过启动应用程序时会看到如下配置信息:

configurationbinder.getvalue找到定义string类型memorycollectionkey1键值并输出。如果我们把获取键名称更改为memorycollectionkey3,再来看看获取键值输出结果:

我们会看到当configurationbinder.getvalue找不到定义string类型memorycollectionkey3键时,则输出默认值。

2.绑定到实体类

可以使用选项模式将文件配置绑定到相关实体类。配置值作为字符串返回,但调用bind 可以绑定poco对象。bind在microsoft.extensions.configuration.binder包中,后者在 microsoft.aspnetcore.app元包中。现在我们在coreweb/models目录下新增一个叫starship.json文件,配置内容如下:

{
  "starship": {
    "name": "uss enterprise",
    "registry": "ncc-1701",
    "class": "constitution",
    "length": 304.8,
    "commissioned": false
  },
  "trademark": "paramount pictures corp. http://www.paramount.com"
}

然后再新增一个对应配置内容的实体模型(/models/starship.cs):

public class starship
{
    public string name { get; set; }
    public string registry { get; set; }
    public string class { get; set; }
    public decimal length { get; set; }
    public bool commissioned { get; set; }
}

构建主机时调用configureappconfiguration以指定应用程序的配置:

public static void main(string[] args)
{
    createwebhostbuilder(args).build().run();
}
public static iwebhostbuilder createwebhostbuilder(string[] args) =>
    webhost.createdefaultbuilder(args)
        .configureappconfiguration((hostingcontext, config) =>
        {
            config.setbasepath(directory.getcurrentdirectory());
            config.addjsonfile(
                "starship.json", optional: true, reloadonchange: true);
        })
        .usestartup<startup>();

示例应用程序调用getsection方法获取json文件中starship键。通过bind方法把starship键属性值绑定到starship类的实例中:

var starship = new starship();
configuration.getsection("starship").bind(starship);
var _starship = starship;

当应用程序启动时会提供json文件配置内容:

3.绑定至对象图

通过第2小节我们学习到如何绑定配置文件内容映射到实例化实体类属性去,同样,配置文件内容也可以绑定到对象图去。现在我们在coreweb/models目录下新增一个叫tvshow.xml文件,配置内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <tvshow>
    <metadata>
      <series>dr. who</series>
      <title>the sun makers</title>
      <airdate>11/26/1977</airdate>
      <episodes>4</episodes>
    </metadata>
    <actors>
      <names>tom baker, louise jameson, john leeson</names>
    </actors>
    <legal>(c)1977 bbc https://www.bbc.co.uk/programmes/b006q2x0</legal>
  </tvshow>
</configuration>

然后再新增一个对应配置内容的实体模型(/models/tvshow.cs),其对象图包含metadata和 actors类:

public class tvshow
{
    public metadata metadata { get; set; }
    public actors actors { get; set; }
    public string legal { get; set; }
}
public class metadata
{
    public string series { get; set; }
    public string title { get; set; }
    public datetime airdate { get; set; }
    public int episodes { get; set; }
}
public class actors
{
    public string names { get; set; }
}

构建主机时调用configureappconfiguration以指定应用程序的配置:
config.addxmlfile(“tvshow.xml”, optional: true, reloadonchange: true);
使用bind方法将配置内容绑定到整个tvshow对象图。将绑定实例分配给用于呈现的属性:

public startup(iconfiguration configuration)
{
    configuration = configuration;
    var tvshow = new tvshow();
    configuration.getsection("tvshow").bind(tvshow);
    var _tvshow = tvshow;
}

当应用程序启动时会提供xml文件配置内容:

还有一种bind方法可以将配置内容绑定到整个tvshow对象图:

public startup(iconfiguration configuration)
{
    configuration = configuration;
    var _tvshow = configuration.getsection("tvshow").get<tvshow>();
}

当应用程序启动时会提供xml文件配置内容:

4.将数组绑定至类

bind方法也支持把配置内容键中的数组绑定到对象类去。公开数字键段(:0:、:1:、… :{n}:)的任何数组格式都能够与poco类数组进行绑定。使用内存配置提供应用程序在示例中加载这些键和值:

public class program
{
    public static dictionary<string, string> arraydict =
            new dictionary<string, string>
            {
                {"array:entries:0", "value0"},
                {"array:entries:1", "value1"},
                {"array:entries:2", "value2"},
                {"array:entries:4", "value4"},
                {"array:entries:5", "value5"}
            };
    public static void main(string[] args)
    {
        createwebhostbuilder(args).build().run();
    }
    public static iwebhostbuilder createwebhostbuilder(string[] args) =>
        webhost.createdefaultbuilder(args)
            .configureappconfiguration((hostingcontext, config) =>
            {
                config.setbasepath(directory.getcurrentdirectory());
                config.addinmemorycollection(arraydict);
            })
            .usestartup<startup>();
}

因为配置绑定程序无法绑定null值,所以该数组跳过了索引#3的值。在示例应用程序中,poco类可用于保存绑定的配置数据:

public class arrayexample
{
    public string[] entries { get; set; }
}

将配置数据绑定至对象:

public startup(iconfiguration configuration)
{
    configuration = configuration;
    var arrayexample = new arrayexample();
    configuration.getsection("array").bind(arrayexample);
    var _arrayexample = arrayexample;
}

还可以使用configurationbinder.get<t>语法,从而产生更精简的代码:

public startup(iconfiguration configuration)
{
    configuration = configuration;
    var _arrayexample = _config.getsection("array").get<arrayexample>();
}

当应用程序启动时会提供内存配置内容:

5.在razor pages页或mvc视图中访问配置

若要访问razorpages页或mvc视图中的配置设置,请为microsoft.extensions.configuration命名空间添加using指令(c#参考:using指令)并将iconfiguration注入页面或视图。
在razor页面页中:

@page
@model indexmodel
@using microsoft.extensions.configuration
@inject iconfiguration configuration
<!doctype html>
<html lang="en">
<head>
    <title>index page</title>
</head>
<body>
    <h1>access configuration in a razor pages page</h1>
    <p>configuration value for 'key': @configuration["key"]</p>
</body>
</html>

在mvc视图中:

@using microsoft.extensions.configuration
@inject iconfiguration configuration
<!doctype html>
<html lang="en">
<head>
    <title>index view</title>
</head>
<body>
    <h1>access configuration in an mvc view</h1>
    <p>configuration value for 'key': @configuration["key"]</p>
</body>
</html>

参考文献:
asp.net core 中的配置