ASP.NET Core 2.0 全局配置项
2017-10-31 00:00
483 查看
问题
如何在 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/
原文地址:http://www.cnblogs.com/zhaopei/p/SSO.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
相关文章推荐
- ASP.NET Core 2.0 WebApi全局配置及日志实例
- ASP.NET Core 2.0 WebApi全局配置及日志
- Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级
- asp.net core webapi项目配置全局路由的方法示例
- ASP.NET Core 2.0 : 五.服务是如何加载并运行的, Kestrel、配置与环境
- ASP.NET Core 2.0系列学习笔记-NLog日志配置文件
- 从头编写 asp.net core 2.0 web api 基础框架 (4) EF配置
- [译]ASP.NET Core 2.0 全局配置项
- [译]ASP.NET Core 2.0 机密配置项
- 用VSCode开发一个asp.net core 2.0+angular 5项目(4): Angular5全局错误处理
- Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例
- asp.net core webapi项目配置全局路由
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
- 一起学ASP.NET Core 2.0学习笔记(二)- ef core2.0 及mysql provider 、Fluent API相关配置及迁移
- ASP.Net Core 2.0 获取Json和Xml格式的配置信息
- 新建Asp.Net Core 2.0 项目配置IIS站点提示500
- [亲测]七步学会ASP.NET Core 2.0怎么发布/部署到Ubuntu Linux服务器并配置Nginx反向代理实现域名访问
- asp.net core2.0中网站发布的时候,怎么样才配置才可以使视图文件不被打包进去?
- [dotnetCore2.0]学习笔记之二: ASP.NET Core中,如何灵活使用静态文件和加载自定义配置
- ASP.NET Core 2.0 配置NLog日志组件