在ASP.NET Core 中,应用程序配置数据可以使用JSON, XML 和 INI格式 和内置环境变量,命令行参数或内存中的集合。

  1.如何获取和设置配置

  ASP.NET Core配置系统针对以前的依赖于System.Configuration和XML配置文件(如Web.config)的ASP,NET 版本进行了重构。新的配置模型提供了精简高效的,能够通过检索多样化提供程序来获取基于键/值对配置的能力。应用程序和框架可以通过新的选择模式访问配置。

  可以在ASP.NET Core应用程序中的Startup类中只实例化一个Configuration示例,然后选择模式来访问各自的设置。

  Configuration类是一个提供读写键/值对能力的Providers集合。如果一个键值对写入Configuration,它不会持久,当源再次读写值时将会丢失。因此至少需要配置一个数据源,使得configuration能正常工作。

  下面通过内存配置演示Configuration处理键值对:

    

  内存配置一般用在一次请求中需要暂存数据的情况,例如,如果管道中有多个中间件,可以在某一个中间件中暂存数据,后面的某一个中使用。

  在开发中一般会把配置值放在一个有层次的数据结构中,例如appsettings.json,在这种情况下,可以使用以: 符号分割(从层次结构的根开始)的键读取值:

{
"ConnectionStrings": {
"DefaultConnection": "Data Source=.;Initial Catalog=AccessManagement;Integrated Security=True"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"AllowedHosts": "*",
"MyOptions": {
"Option1": "ww",
"Option2":
}
}

  在应用程序中通过Configuration获取配置的连接字符串,可以通过ConnectionStrings:DefaultConnection读取ConnectionStrings的设置,也可以通过GetConnectionString扩展方法加参数"DefaultConnection"来获取。

    

  应用程序所需要的设置和指定配置的机制都可以通过使用选择模式解耦。创建自己的配置类时,可以是几个不同的类,分别对应不同的配置组,然后通过选项服务注入到应用程序中。这样就可以通过配置或其他所选择的机制来设置了。

  2.使用内置数据源

  开发时并不局限于必须使用单个配置提供程序,可以把多个配置提供程序组合在一起。

  扩展方法支持为配置添加额外的配置文件提供程序。这些方法能被独立的或链式调用在ConfigurationBuilder实例之上:  

    public Startup()
{
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
var config = builder.Build(); var _config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
}

    指定配置提供程序的顺序很重要,这将影响他们的设置被应用的优先级:

public Startup(IConfiguration configuration,IHostingEnvironment env)
{ var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(“appsettings.json",optional:true,reloadOnChange:true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true); //配置环境变量
builder.AddEnvironmentVariables();
Configuration = builder.Build();
} public IConfiguration Configuration { get; }

  IHostingEnvironment 服务用于获取当前环境。在Development环境中,AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true)将会查找appsettings.Development.json配置文件,并覆盖appsettings.json中存在的值。同样环境变量也会覆盖它们两个的值。

  一旦将指定文件作为配置源,就可以选择当文件发生变化后,是否重新再付这部分的配置,reloadOnChange:true。

  3.使用选项和配置对象

  选择模式可使用自定义的配置类表示一组相关设置。这个配置类需要为配置项提供公开的 属性和一个无参的构造函数。可以根据应用程序的功能分解为多个配置对象。

  下面自定义appsettings.json的配置类,并使用:

  先创建配置类

namespace MVCTest
{
public class AppSettingOptions
{
public DefaultConnec ConnectionStrings { get; set; }
public string AllowedHosts { get; set; }
} public class DefaultConnec
{
public string DefaultConnection { get; set; }
}
}

  在ConfigureServices中调用选项服务:

        public Startup(IConfiguration configuration,IHostingEnvironment env)
{
//Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json",optional:true,reloadOnChange:true)
//.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true); //配置环境变量
builder.AddEnvironmentVariables();
Configuration = builder.Build();
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();//提供依赖注入
services.Configure<AppSettingOptions>(Configuration); //绑定配置选项
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

    在HomeController中使用:

public class HomeController : Controller
{
private readonly IOptions<AppSettingOptions> _options;
public HomeController(IOptions<AppSettingOptions> options,)
{
_options = options;
}
public static Logger nlog = LogManager.GetCurrentClassLogger();
public IActionResult Index()
{
var AllowedHosts = _options.Value.AllowedHosts;
var DefaultConnection = _options.Value.ConnectionStrings.DefaultConnection;
}
}

    结果:

      

    

  当通过绑定选项来配置选项类型的每一个属性时,实际上是绑定到每一个配置键。配置键是大小写不敏感的。

  当通过调用services.Configure<AppSettingOptions>(Configuration);代码,将一个IConfigureOptions<AppSettingOptions>服务加入服务容器,是为了后面应用程序或框架能通过IOptions<AppSettingOptions>服务来获取配置。若想从其他途径(从数据库通过EF获取)获取配置,可以使用ConfigureOptions<TOptions>扩展方法直接指定经过定制的IConfigureOptions<TOptions>服务。

  其他方法:

//通过代码编写
services.Configure<AppSettingOptions>(options=>
{
options.AllowedHosts = "test";
});
//只配置部分
services.Configure<AppSettingOptions>(Configuration.GetSection("ConnectionStrings"));

ASP.NET Core 配置文件的更多相关文章

  1. asp.net core配置文件

    读取配置文件 asp.net core使用appsettings.json代替传统.net framework的web.config中的<appSettings>节点.它的数据格式变成了j ...

  2. ASP.NET Core 配置文件(无处不在的依赖注入)

    前烟: .NET Core 中取消了以往的 XML 节点配置文件,改用了 *.json 格式. 在 Startup.cs 文件中,构造方法 build appsetting.json 文件, 本文主要 ...

  3. .NET 黑魔法 - asp.net core 配置文件的"对象存储"

    来,全都是干货. 我们都知道在Framework版本的mvc项目中,配置数据是通过web.config里的appSettings节点配置,我们不得不写一些读取配置文件字符串的类,比如保存在静态的变量中 ...

  4. asp.net core 配置文件动态更新

    IOptions<T> //站点启动后,获取到的值永远不变 IOptionsSnapshot<T> //站点启动后,每次获取到的值都是配置文件里的最新值 (reloadOnCh ...

  5. net core体系-web应用程序-4net core2.0大白话带你入门-6asp.net core配置文件

    asp.net core配置文件   读取配置文件 asp.net core使用appsettings.json代替传统.net framework的web.config中的<appSettin ...

  6. 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 我们在 读取配置文件(一) appsettings.json 中介绍了,如何读取appsettings.json. 但随之产生 ...

  7. 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 在我们之前的Asp.net mvc 开发中,一提到配置文件,我们不由的想到 web.config 和 app.config,在 ...

  8. ASP.NET Core开发-读取配置文件Configuration

    ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML ...

  9. asp.net core轻松入门之MVC中Options读取配置文件

    接上一篇中讲到利用Bind方法读取配置文件 ASP.NET Core轻松入门Bind读取配置文件到C#实例 那么在这篇文章中,我将在上一篇文章的基础上,利用Options方法读取配置文件 首先注册MV ...

随机推荐

  1. Nginx应用优化

    案例环境: 系统类型 IP地址 主机名 所需软件 Centos 6.5 192.168.100.150 www.linuxfan.cn nginx-1.6.2.tar.gz 一.Nginx隐藏版本号 ...

  2. 【Servlet】The servlets named [ByteServlet] and [content.ByteServlet] are both mapped to the url-pattern [ByteServlet] which is not permitted

    创建时间:6.30 The servlets named [ByteServlet] and [content.ByteServlet] are both mapped to the url-patt ...

  3. django rest framework 解析器组件 接口设计,视图组件 (2)

    1. 使用视图组件进行接口优化 1.1 使用视图组件的mixin进行接口逻辑优化 - 导入mixin from rest_framework.mixinx import ( ListModelMix, ...

  4. V4L2视频采集原理

    一.简介 Video for Linuxtwo(Video4Linux2)简称V4L2,是V4L的改进版.V4L2是linux操作系统下用于采集图片.视频和音频数据的API接口,配合适当的视频采集设备 ...

  5. Scrapy笔记08- 文件与图片

    Scrapy笔记08- 文件与图片 Scrapy为我们提供了可重用的item pipelines为某个特定的Item去下载文件. 通常来说你会选择使用Files Pipeline或Images Pip ...

  6. Java多态中成员的调用的特殊情况

    1.当子类和父类中有相同的成员属性的时候 public class Demo { public static void main(String[] args) { Father son=new Son ...

  7. Active Ball

    Active Ball is a simple game. All you need to do is aim at the food and shoot it, then collect the m ...

  8. MySQL基于 amoeba.xml的读写分离

    1.准备两台服务器  centos7 192.168.52.35 192.168.52.36 2.关闭防火墙 [root@localhost ~]# systemctl stop firewalld ...

  9. zy的日志报表执行有问题。crontab显示执行了任务,代码中应该有问题

    crontab定时任务在日志记录中是执行了 但是在执行脚本的过程中报错了, 找不到问题原因,以后也要在脚本中加入日志记录, 但是奇怪的是在中午和晚上是正常的, 应该是那个时间段的判断逻辑有问题,导致程 ...

  10. Spring Boot 知识笔记(thymleaf模板引擎)

    一.pom.xml中引入 <dependency> <groupId>org.springframework.boot</groupId> <artifact ...