我是靠谱客的博主 健康钻石,这篇文章主要介绍.net core中配置文件的使用,现在分享给大家,希望可以做个参考。

1.准备配置文件appsettings.json

Debug时读取的是appsettings.Development.json

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{ "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 新建一个配置文件对象

复制代码
1
2
3
4
5
6
7
8
9
10
11
namespace TestApi.Configuration { public class DaoConfig { //这里可以初始化配置文件中该节点的名称,可以直接当作一个参数使用 public string ConfigName = "DAO"; public string Postgre { get; set; } public string PartitionColumn { get; set; } } }

2.2 在控制器中使用配置文件中的配置

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//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>(); } } }

最后

以上就是健康钻石最近收集整理的关于.net core中配置文件的使用的全部内容,更多相关.net内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部