问题
如何在 ASP.NET Core 2.0 应用程序中读取全局配置项?
答案
首先新建一个空项目,并添加两个配置文件:
1. appsettings.json
{ ?"Section1": { ???"SettingA": "ValueA", ???"SettingB": "ValueB" ?}, ?"Section2": { ???"SettingC": "ValueC" ?}}
2. appsettings.Development.json
{ ?"Section1": { ???"SettingA": "Dev_ValueA" ?}, ?"Section2": { ???"SettingC": "Dev_ValueC" ?}}
Visual Studio会自动识别两者的关系,并在解决方案层次结构中展示如下:
然后创建相应的POCO类,分别对应于几个配置节点:
public class AppSettings{ ???public AppSettingsSection1 Section1 { get; set; } ???public AppSettingsSection2 Section2 { get; set; }}public class AppSettingsSection1{ ???public string SettingA { get; set; } ???public string SettingB { get; set; }}public class AppSettingsSection2{ ???public string SettingC { get; set; }}
在Startup.cs文件中,创建接收 IConfiguration 的构造函数:
public static IConfiguration Configuration { get; private set;}public Startup(IConfiguration config){ ???Configuration = config;}
然后在 ConfigureServices() 方法中添加Options服务,并设置依赖项:
public void ConfigureServices(IServiceCollection services){ ???services.AddOptions(); ???services.Configure<AppSettings>(Configuration);}
最后,将配置项作为IOptions接口注入中间件的构造函数,其中泛型类型T就是我们刚才定义的POCO类:
public class HelloWorldMiddleware{ ???private readonly RequestDelegate _next; ???private readonly AppSettings _settings; ???public HelloWorldMiddleware(RequestDelegate next, IOptions<AppSettings> options) ???{ ???????_next = next; ???????_settings = options.Value; ???} ???public async Task Invoke(HttpContext context) ???{ ???????var jsonSettings = JsonConvert.SerializeObject(_settings, Formatting.Indented); ???????await context.Response.WriteAsync(jsonSettings); ???}}public static class UseHelloWorldInClassExtensions{ ???public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder app) ???{ ???????return app.UseMiddleware<HelloWorldMiddleware>(); ???}}
在Startup.cs的 Configure() 方法中,将此中间件注入到请求管道中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ ???app.UseHelloWorld();}
运行,此时页面显示:
讨论
ASP.NET Core 拥有一个简单的机制来从各种数据源(比如JSON文件,环境变量,甚至是自定义数据源)中读取应用程序设置。然后通过依赖注入,方便的使用这些配置项。
尽管这一切看起来很魔幻(我们的设置究竟是如何加载的!),ASP.NET Core 2.0隐藏了从数据源中读取配置项的细节,这些内容本应该存在于Program.cs文件中WebHost的CreateDefaultBuilder()方法中。IConfiguration随后被添加到服务容器中,并在应用程序的其他部分保持可用,我们使用Startup中的此接口来添加配置项。为了观察这个过程,请将Program.cs文件中的BuildWebHost()方法替换为如下内容,得到的结果是一样的:
public static IWebHost BuildWebHost(string[] args) => ???WebHost.CreateDefaultBuilder(args) ???????.UseStartup<Startup>() ???????.ConfigureAppConfiguration((context, builder) => ???????{ ???????????var env = context.HostingEnvironment; ???????????builder.AddJsonFile("appsettings.json", ????????????????????????optional: true, reloadOnChange: true) ??????????????????.AddJsonFile($"appsettings.{env.EnvironmentName}.json", ????????????????????????optional: true, reloadOnChange: true); ???????????if (env.IsDevelopment()) ???????????{ ???????????????var appAssembly = Assembly.Load( ???????????????????new AssemblyName(env.ApplicationName)); ???????????????if (appAssembly != null) ???????????????{ ???????????????????builder.AddUserSecrets(appAssembly, optional: true); ???????????????} ???????????} ???????????builder.AddEnvironmentVariables(); ???????????if (args != null) ???????????{ ???????????????builder.AddCommandLine(args); ???????????} ???????}) ???????.Build();
在上面的解决方案中,我们提供了两个JSON文件数据源。需要记着的一点是,这些文件按照顺序被依次读取,后面的数据源会覆盖前面的数据源。你也可以在上面的运行结果中注意到,SettingB配置项来自于第一个配置文件,而其他两个配置项都来自于第二个配置文件。
注意:Startup.cs中的IConfiguration实例拥有public static修饰符,因此可以在整个应用程序期间使用此实例:
var valueA = Config["Section1:SettingA"];
然而,更好的办法是将配置项读入一个类型化的POCO类,并将其作为依赖项注入中间件或者控制器。上面的示例正好展示了这个模式。
你也可以为不同的配置节定义不同的POCO类,并使用IConfiguration的GetSection()方法来读取。
====start by sanshi=========================
下面我们简单扩展之前的示例,来读取不同的配置节:
public void ConfigureServices(IServiceCollection services){ ???services.AddOptions(); ???services.Configure<AppSettings>(Configuration); ???services.Configure<AppSettingsSection1>(Configuration.GetSection("Section1"));}
更新中间件代码,此时向中间件的构造函数注入两个依赖项:
public class HelloWorldMiddleware{ ???private readonly RequestDelegate _next; ???private readonly AppSettings _settings; ???private readonly AppSettingsSection1 _settingsSection1; ???public HelloWorldMiddleware(RequestDelegate next, IOptions<AppSettings> options, IOptions<AppSettingsSection1> optionsSection1) ???{ ???????_next = next; ???????_settings = options.Value; ???????_settingsSection1 = optionsSection1.Value; ???} ???public async Task Invoke(HttpContext context) ???{ ???????var jsonSettings = JsonConvert.SerializeObject(_settings, Formatting.Indented); ???????var jsonSettingsSection1 = JsonConvert.SerializeObject(_settingsSection1, Formatting.Indented); ???????await context.Response.WriteAsync("AppSettings:\n" + jsonSettings + "\n\nAppSettings - Section1:\n" + jsonSettingsSection1); ???}}
运行,此时页面显示:
====end by sanshi=========================
当然,我们也可以手工设置配置项的值,通过使用IServiceCollection.Configure的重载方法并接收强类型的lambda表达式:
====start by sanshi=========================
修改ConfigurationServices()方法,手工设置配置项:
public void ConfigureServices(IServiceCollection services){ ???services.AddOptions(); ???????services.Configure<AppSettings>(options => ???{ ???????options.Section1 = new AppSettingsSection1(); ???????options.Section1.SettingA = "SettingA Value"; ???????options.Section1.SettingB = "SettingB Value"; ???});}
运行,此时页面效果:
====end by sanshi=========================
源代码下载
原文:https://tahirnaushad.com/2017/08/15/asp-net-core-configuration/
[译]ASP.NET Core 2.0 全局配置项
原文地址:http://www.cnblogs.com/sanshi/p/7719163.html