(12)ASP.NET Core 中的配置二(Configuration)
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>//</airdate>
<episodes></episodes>
</metadata>
<actors>
<names>Tom Baker, Louise Jameson, John Leeson</names>
</actors>
<legal>(c) 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 中的配置
(12)ASP.NET Core 中的配置二(Configuration)的更多相关文章
- 3、带你一步一步学习ASP.NET Core中的配置之Configuration
如果你是刚接触ASP.NET Core的学习的话,你会注意到:在ASP.NET Core项目中,看不到.NET Fraemwork时代中的web.config文件和app.config文件了.那么你肯 ...
- (11)ASP.NET Core 中的配置一(Configuration)
1.前言 ASP.NET Core在应用程序上引入Microsoft.Extensions.Configuration配置,可以支持多种方式配置,包括命令行配置.环境变量配置.文件配置.内存配置,自定 ...
- 聊聊ASP.NET Core中的配置
作为软件开发人员,我们当然喜欢一些可配置选项,尤其是当它允许我们改变应用程序的行为而无需修改或编译我们的应用程序时.无论你是使用新的还是旧的.NET时,可能希望利用json文件的配置.在这篇文章中, ...
- 翻译 - ASP.NET Core 基本知识 - 配置(Configuration)
翻译自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0 ASP ...
- ASP.NET Core 中的配置
目录 以键-值对的形式读取配置 多环境配置 读取结构化的配置数据 参考 .NET Core 定义配置的方式不同于之前 NET 版本,之前是依赖于 System.Configuration 的 app. ...
- ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置
前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...
- ASP.NET Core中的配置
配置 参考文件点击跳转 配置来源 命令行参数 自定义提供程序 目录文件 环境变量 内存中的.NET 对象 文件 默认配置 CreateDefaultBuilder方法提供有默认配置,在这个方法中会接收 ...
- IdentityServer4在Asp.Net Core中的应用(二)
继续上次授权的内容,客户端模式后我们再说以下密码模式,先回顾下密码模式的流程: 我们还是使用上次的代码,在那基础上修改,在IdentityServer4里面有一个IdentityServer4.Tes ...
- (13)ASP.NET Core 中的选项模式(Options)
1.前言 选项(Options)模式是对配置(Configuration)的功能的延伸.在12章(ASP.NET Core中的配置二)Configuration中有介绍过该功能(绑定到实体类.绑定至对 ...
随机推荐
- 【工具】读取proprtties工具类
获取properties内容: 基本的使用看网络上大多是这样的,使用时注意线程安全以及读写的实时性问题. 1.直接通过流读取(反射): InputStream inStream = this.get ...
- CSS3 - vue中纯css实现柱状图表效果
背景 以前我们制作柱状图都用echarts或者其他同类型的图表插件 这次是个移动端的需求,而且这个图表需要动画 使用echarts就会显得过重,而且动画达不到我想要的效果(主要是我自己愚蠢想不到好的动 ...
- K8s集群部署(二)------ Master节点部署
Master节点要部署三个服务:API Server.Scheduler.Controller Manager. apiserver提供集群管理的REST API接口,包括认证授权.数据校验以 及集群 ...
- C++ 洛谷P1230 智力大冲浪
题目描述 小伟报名参加中央电视台的智力大冲浪节目.本次挑战赛吸引了众多参赛者,主持人为了表彰大家的勇气,先奖励每个参赛者m元.先不要太高兴!因为这些钱还不一定都是你的?!接下来主持人宣布了比赛规则: ...
- c++2的幂次方
c++2的幂次方 题目描述 任何一个正整数都可以用2的幂次方表示. 同时约定用括号来表示方次,即a的b次,可以表示为a(b). 由此可知,137可以表示为: 2(7)+2(3)+2(0) 进一步: ...
- zookeeper的客户端应用
什么zookeeper? ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件.它是一个为分布式应用提供 ...
- Nginx+Lua+MySQL/Redis实现高性能动态网页展现
Nginx结合Lua脚本,直接绕过Tomcat应用服务器,连接MySQL/Redis直接获取数据,再结合Lua中Template组件,直接写入动态数据,渲染成页面,响应前端,一次请求响应过程结束.最终 ...
- Python一秒提供Rest接口
Python一秒提供Rest接口 使用的是Anaconda安装的Python环境; 新建py文件(例如:restapi.py) # -*- coding: utf-8 -*- from flask i ...
- 使用flink Table &Sql api来构建批量和流式应用(2)Table API概述
从flink的官方文档,我们知道flink的编程模型分为四层,sql层是最高层的api,Table api是中间层,DataStream/DataSet Api 是核心,stateful Stream ...
- 获取文件版本(IE)
GetFileInfoCUIAction::GetFileVersion2GetSystemDirectory WCHAR szConfigFile[MAX_PATH + 1]; ::G ...