.net core中配置文件的使用

1.准备配置文件appsettings.json

Debug时读取的是appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ApplicationID": "DessInsuranceSystem",
  "DAO": {
    "Postgre": "User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=MyDB;Pooling=true;",
    "PartitionColumn": "TerantId"
  }
}

2.具体使用

2.1 新建一个配置文件对象
namespace TestApi.Configuration
{
    public class DaoConfig
    {
        //这里可以初始化配置文件中该节点的名称,可以直接当作一个参数使用
        public string ConfigName = "DAO";
        public string Postgre { get; set; }
        public string PartitionColumn { get; set; }
    }
}

2.2 在控制器中使用配置文件中的配置
//IConfiguration 所在的命名空间
using Microsoft.Extensions.Configuration;
namespace TestApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
         //通过构造函数进行注入
        private readonly IConfiguration _configuration;
        public WeatherForecastController(IConfiguration configuration)
        {     
            _configuration = configuration;
        }

        public IActionResult Get()
        {
            /*
             * 获取配置文件
             * 1.构造函数注入 IConfiguration
             * 2.使用配置文件
             * 2.1 获取单个的配置文件 _configuration["key"]
             * 2.2 获取多层配置文件 _configuration["key:key1"] 或者是 _configuration.GetSection["key:key1"].Get<string>()
             * 2.3 获取配置文件对象 
             *      jwtSettings setting=new jwtSettings();
             *      _configuration.GetSection["DAO"].Bind(setting)
             * **/

            //获取配置文件对象(需要先实例化一个配置文件对象)
            DaoConfig daoConfig = new DaoConfig();
            //将从配置文件中获取到的数据绑定到 daoConfig 中
            _configuration.GetSection(daoConfig.ConfigName).Bind(daoConfig);
            //最后一行代码也可以写作下边这样(Get类型为要转换的类型,也可以是String)
            _configuration.GetSection(daoConfig.ConfigName).Get<DaoConfig>();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值