ASP.NET Core 2.0 全局配置项
来源:互联网 发布:猪八戒的网络推广 编辑:程序博客网 时间:2024/06/08 07:01
问题
如何在 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 全局配置项
- ASP.NET Core MVC 配置全局路由前缀
- ASP.NET Core MVC 配置全局路由前缀
- asp.net core 全局注入
- Asp.Net Core-配置
- Asp.Net Core-Identity 配置
- ASP.NET Core 配置身份验证
- Asp.net core mvc里面怎么添加全局的Filter
- ASP.NET Core MVC 中设置全局异常处理方式
- .Net Core 全局配置读取管理方法 ConfigurationManager
- asp.net core 获取 appsettings.json 配置
- ASP.NET Core中配置CORS
- Amazing ASP.NET Core 2.0
- 在IIS上配置ASP.NET的全局配置
- ASP.NET Core的配置(2):配置模型详解
- ASP.NET Core的配置(1):读取配置信息
- ASP.NET Core 中的依赖项管理
- Programming Microsoft ASP.NET 2.0 Core Reference
- Java后台接收js数组对象,并解析
- Pattern用法(正则表达式)
- C/C++零碎知识点
- 短信发送pdu格式
- 微软Tech Summit 2017,天安门前看升旗
- ASP.NET Core 2.0 全局配置项
- java八大基本数据类型及类型转换
- 浅析C#中单点登录的原理和使用
- mybatis 动态创建表
- Android金融支付常见加解密算法及安全防护
- python实践项目(三)
- 基于CentOS 7配置Nginx反向代理
- VMware虚拟机中ubuntu 16.04.3 安装、root密码设置、Xshell无法连接、ubuntu重启关机命令汇总
- 大佬的JAVA游戏服务开发经验