.NET Core技术研究-最实用最常用的配置读取方式

原文: .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

  我们通过下面的代码,输出配置提供程序的加载顺序:

?
1
2
3
4
5
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文件

?
1
2
3
4
5
6
7
8
9
10
{
   "Logging": {
     "LogLevel": {
       "Default": "Information",
       "Microsoft": "Warning",
       "Microsoft.Hosting.Lifetime": "Information"
     }
   },
   "AllowedHosts": "*"
}

 通过代码读取配置

?
1
2
3
4
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[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配置示例代码:

?
1
2
Logging logConfig = new Logging();
<strong>Configuration.GetSection( "Logging" ).Bind(logConfig);</strong>
?
1
<strong> var lifetime = Configuration[ "Logging:LogLevel:Microsoft.Hosting.Lifetime" ];</strong>
?
1
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时指定的变量:    

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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读取配置之后。

   这个地方有个分隔符的注意点,因为 :并不是在所有平台上都支持,建议统一使用__(双下划线),运行时会将__统一替换为:

   先通过以下命令,设置环境变量:

?
1
2
set Key1= "Value1"
set Logging__LogLevel__Customer=Information

   代码中读取环境变量的配置 

?
1
2
3
4
5
6
7
8
9
10
11
public static IHostBuilder CreateHostBuilder( string [] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostBuilder, config) =>
                {
                    config.AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseEnvironment( "Development" );
                    webBuilder.UseStartup<Startup>();                   
                });

  修改Startup中Configure方法:读取配置并输出

?
1
2
3
4
var key1Value = Configuration[ "Key1" ];
var logLevel = Configuration[ "Logging:LogLevel:Customer" ];
Console.WriteLine( "key1Value:" + key1Value + "\n" );
Console.WriteLine( "logLevel:" + logLevel + "\n" );

  

四、命令行参数读取

   命令行配置提供程序CommandLineConfigurationProvider,将在以下配置源之后从命令行参数键值对加载配置:

  1.    appsettings.json和appsettings。Environment。json文件
  2.    开发环境中的应用程序机密(秘密管理器)
  3.    环境变量

   继续使用第三章中的示例工程,新建CMD命令行,输入以下dotnet run指令:

?
1
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读取配置:

?
1
2
var value = System.Configuration.ConfigurationManager.AppSettings[ "ConfigKey1" ];
Console.WriteLine( "ConfigKey1:" + value + "\n" );

以上就是ASP.NET Core常用的“应用程序配置文件”,“环境变量”,“命令行参数”,“app.config” 配置读取方式,分享给大家。

周国庆

2020/4/1

   

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12688643.html