.NET|.NET Core读取配置文件

1. 说明 默认情况下读取配置Configuration的默认优先级:ConfigureAppConfiguration(自定义读取)>CommandLine(命令行参数)>Environment(环境变量)>appsetting.json(默认配置文件)>UseSetting的顺序
原因:读取配置的顺序是后来者居上模式,后来注册的会优先被读取到。
2. 获取配置 2.1 获取单个项

//值是数组 var a0 = Configuration.GetSection("RabbitMQ:Hosts").Get(); //获取数组第一个 var a0 = Configuration["RabbitMQ:Hosts:0"]; //值是int类型 var a1 = Configuration.GetValue("RabbitMQ:Port"); //值是字符串var a2 = Configuration.GetValue("RabbitMQ:UserName"); var a2 = Configuration["RabbitMQ:UserName"];

2.2 映射项到模型类
模型类
public class RabbitMQConfig{public const string RabbitMQ = "RabbitMQ"; public string[] Hosts { get; set; }public int Port { get; set; }public string UserName { get; set; }public string Password { get; set; }public string VirtualHost { get; set; }}

appsettings
"RabbitMQ": {"Hosts": [ "xxx.xxx.xxx.xxx" ],"Port": 5672,"UserName": "admin","Password": "xxxxxx","VirtualHost": "myQueue"}

2.2.1 注入模型类
//startup配置 services.Configure(Configuration.GetSection(RabbitMQConfig.RabbitMQ)); //获取数据private readonly RabbitMQConfig _rabbitMQConfig; public WeatherForecastController(IOptions options){_rabbitMQConfig = options.Value; }

2.2.2 映射项到模型类
var info = new RabbitMQConfig(); Configuration.Bind(RabbitMQConfig.RabbitMQ, info); //orConfiguration.GetSection(RabbitMQConfig.RabbitMQ).Bind(info);

【.NET|.NET Core读取配置文件】到此这篇关于.NET Core读取配置文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读