ASP.NET Core 中的配置

 前言

配置在我们开发过程中必不可少,ASP.NET中的配置在 Web.config中。也可配置在如:JSON、XML、数据库等(但ASP.NET并没提供相应的模块和方法)。

ASP.NET CoreWeb.config已经不存在了(但如果托管到 IIS 的时候可以使用 web.config 配置 IIS),

而是用appsettings.jsonappsettings.(Development、Staging、Production).json配置文件

(可以理解为ASP.NET中的Web.configWeb.Release.config的关系)。

下面我们一起看下ASP.NET Core 中的配置

基础用法

HomeController.cs

[ApiController] public class HomeController : ControllerBase {     private readonly IConfiguration _configuration;     public HomeController(IConfiguration configuration)     {         _configuration = configuration;     }      [HttpGet("/")]     public dynamic Index()     {         return JsonConvert.SerializeObject(new         {             ConnectionString = _configuration["ConnectionString"],             Child1 = _configuration["Parent:Child1"],             Grandchildren = _configuration["Parent:Child2:Grandchildren"]         });     } }

返回结果:

{     "ConnectionString": "data source=.;initial catalog=TEST;user id=sa",     "Child1": "child",     "Grandchildren": "grandchildren" }

对应appsettings.json的值:

{     "ConnectionString": "data source=.;initial catalog=TEST;user id=sa;password=123",     "Parent": {         "Child1": "child1",         "Child2": "child2"     } }

需要注意的:

  • 键不区分大小写。 例如,ConnectionString 和 connectionstring 被视为等效键。
  • 如果键名相同(包含所有加载的配置文件),以最后一个值为准。

    所以appsettings.(Development、Staging、Production).json会覆盖appsettings.json的配置信息。

    • 多层级用:来分割,但如果是环境变量则存在跨平台问题 查看具体细节
    • 上面这种写法是没缓存的即:appsettings.json修改后,获取的值会立即改变

绑定到对象 IOptions<TestOptions>

对于_configuration["Parent:Child2:Grandchildren"]的写法对程序员来说肯定很反感,下面我们看下把配置文件绑定到对象中。

  1. 关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信