.NET Core技术研究-配置读取
升级ASP.NET Core后,配置的读取是第一个要明确的技术。原先的App.Config、Web.Config、自定义Config在ASP.NET Core中如何正常使用。有必要好好总结整理一下,相信大家都会用到。
首先,看一下ASP.NET Core中的配置提供程序(Configuration Providers):
一、配置提供程序(Configuration Providers)
ASP.NET Core 使用一个或多个配置提供程序来读取配置:
- 应用程序设置文件(配置文件),例如appsettings.json
- 环境变量:Environment variables
- 命令行参数:Command-line arguments
- 自定义的配置提供程序
- 目录文件
- 内存中的.NET对象(内存中的配置类)
- Azure Key Vault,详细说明参考这个连接:https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.0&tabs=windows
- Azure应用程序配置:Azure App Configuration
我们通过下面的代码,输出配置提供程序的加载顺序:
var configRoot = (IConfigurationRoot)Configuration;
foreach (var provider in configRoot.Providers.ToList())
{
Debug.WriteLine(provider.ToString() + "\n");
}
输出有5个:
- Microsoft.Extensions.Configuration.ChainedConfigurationProvider:链式的配置提供程序,可以添加已有的IConfiguration,作为一个配置源
- JsonConfigurationProvider for 'appsettings.json' (Optional):读取appsettings.json文件
- JsonConfigurationProvider for 'appsettings.Development.json' (Optional):按环境读取不同的appsettings.json文件,例如appsettings.Development.json、appsettings.Production.json
- EnvironmentVariablesConfigurationProvider:读取环境变量
- CommandLineConfigurationProvider:读取命令行参数配置
接下来我们我们重点介绍“应用程序配置文件”,“环境变量”,“命令行参数”,“app.config” 这四种最常用的配置读取方式,通过代码的方式,示例给大家:
二、读取应用程序设置文件appsettings.json
我们使用ASP.NET Core工程中默认的appsettings.json文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
通过代码读取配置
var allowedHosts = Configuration["AllowedHosts"];
var defaultLogLevel = Configuration["Logging:LogLevel:Default"];
Debug.WriteLine("allowedHosts:" + allowedHosts + "\n");
Debug.WriteLine("defaultLogLevel:"+defaultLogLevel + "\n");
实际输出:
allowedHosts:*
defaultLogLevel:Information
如果想读取整个的LogLevel对象,如何实现?
新建LogLevel类和Logging类
[DataContract]
public class LogLevel
{
[DataMember(Name = "Default")]
public string Default { get; set; } [DataMember(Name = "Microsoft")]
public string Microsoft { get; set; } [DataMember(Name ="Microsoft.Hosting.Lifetime")]
public string MicrosoftHostingLifetime { get; set; } } [DataContract]
public class Logging
{
[DataMember]
public LogLevel LogLevel { get; set; }
}
读取Logging配置示例代码:
Logging logConfig = new Logging();
Configuration.GetSection("Logging").Bind(logConfig);
var lifetime = Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"];
logConfig.LogLevel.MicrosoftHostingLifetime = lifetime;
上述代码中,对Lifetime属性的设置,通过以下方式实现,Bind的方式因为key匹配的问题,无法完成匹配。
Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"];
这个地方补充一个带环境类型的应用设置文件的价值顺序:比如说按环境分appsettings.json文件
默认的JsonConfigurationProvider ,按以下顺序加载 appsettings.json文件:
① appsettings.json
② appsettings.Environment.json,例如appsettings.Development.json ,appsettings.Production.json
关于appsettings.Environment.json,Environment的设置主页在Program时指定的变量:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
} public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseEnvironment("Development");
webBuilder.UseStartup<Startup>();
});
}
三、环境变量读取
按照配置的加载顺序,EnvironmentVariablesConfigurationProvider从环境变量中读取配置信息,在appsettings.json和Secret manager读取配置之后。
这个地方有个分隔符的注意点,因为 :并不是在所有平台上都支持,建议统一使用__(双下划线),运行时会将__统一替换为:
先通过以下命令,设置环境变量:
set Key1="Value1"
set Logging__LogLevel__Customer=Information
代码中读取环境变量的配置
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostBuilder, config) =>
{
config.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseEnvironment("Development");
webBuilder.UseStartup<Startup>();
});
修改Startup中Configure方法:读取配置并输出
var key1Value = Configuration["Key1"];
var logLevel = Configuration["Logging:LogLevel:Customer"];
Console.WriteLine("key1Value:" + key1Value + "\n");
Console.WriteLine("logLevel:" + logLevel + "\n");
四、命令行参数读取
命令行配置提供程序CommandLineConfigurationProvider,将在以下配置源之后从命令行参数键值对加载配置:
- appsettings.json和appsettings。Environment。json文件
- 开发环境中的应用程序机密(秘密管理器)
- 环境变量
继续使用第三章中的示例工程,新建CMD命令行,输入以下dotnet run指令:
dotnet run Key1="Value1" Logging:LogLevel:Customer="Information"
五、app.config读取
这个场景最大的作用就是兼容原有ASP.NET Web.Config文件!
首先添加Nuget引用:System.Configuration.ConfigurationManager
新增app.config文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConfigKey1" value="Value" />
</appSettings>
</configuration>
使用原有ConfigurationManager读取配置:
var value = System.Configuration.ConfigurationManager.AppSettings["ConfigKey1"];
Console.WriteLine("ConfigKey1:" + value + "\n");
以上就是ASP.NET Core常用的“应用程序配置文件”,“环境变量”,“命令行参数”,“app.config” 配置读取方式,分享给大家。
周国庆
2020/4/1
最新文章
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(50)-Easyui 扁平化皮肤
- SPSS 统计图形
- hdu 4952 Number Transformation (找规律)
- 中国区Windows Azure 提供的功能以及与国外的差异
- windows+apache2.2.9+php5.4.41+mysql安装
- 区别assign VS weak,__block VS __weak
- Smarty环境配置
- jQuery旋转插件
- [原创].NET 业务框架开发实战之九 Mapping属性原理和验证规则的实现策略
- OpenWRT GPIO人口控制 WLED
- windows下的python flask环境搭建
- start with connect by prior 递归查询用法,很实用
- Ubuntu14.04 安装vmware虚拟机
- WEB学习笔记14-HTML5新特性的使用
- 剑指Offer 36. 两个链表的第一个公共结点 (链表)
- SQL With (递归CTE查询)
- A. Srdce and Triangle 几何题
- 插入排序的Java代码实现
- python 爬虫 scrapy1_官网教程
- Linux top和负载的解释(转载)
热门文章
- XXE学习(一)——XML基础
- PhaserJS 3 屏幕适配时的小坑 -- JavaScript Html5 游戏开发
- 说一说Vue(2.0)组件的通信方式
- 在服务器上保存图片没有权限该怎么办?Permission denied:xxxxxx
- Java 读取Word中的脚注、尾注
- 基于springboot多模块项目使用maven命令打成war包放到服务器上运行的问题
- 音频相关 ALSA ffmpeg ffplay 命令用法 g7xx
- 一起了解 .Net Foundation 项目 No.19
- 深入理解yield from语法
- Leetcode 1160: 拼写单词