首页 > Web开发 > 详细

.Net之配置文件

时间:2021-05-04 13:59:17      阅读:20      评论:0      收藏:0      [点我收藏+]

1. 说明

默认情况下读取配置Configuration的默认优先级:ConfigureAppConfiguration(自定义读取)>CommandLine(命令行参数)>Environment(环境变量)>appsetting.json(默认配置文件)>UseSetting的顺序

原因:读取配置的顺序是后来者居上模式,后来注册的会优先被读取到。

2. 获取配置

2.1 获取单个项

//值是数组
 var a0 = Configuration.GetSection("RabbitMQ:Hosts").Get<string[]>();
//获取数组第一个
 var a0 = Configuration["RabbitMQ:Hosts:0"];
//值是int类型
 var a1 = Configuration.GetValue<int>("RabbitMQ:Port");
//值是字符串
var a2 = Configuration.GetValue<string>("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": "123456",
    "VirtualHost": "myQueue"
  }

2.2.1 注入模型类

//startup配置 
services.Configure<RabbitMQConfig>(Configuration.GetSection(RabbitMQConfig.RabbitMQ));
//获取数据
private readonly RabbitMQConfig _rabbitMQConfig;
public WeatherForecastController(IOptions<RabbitMQConfig> options)
{
    _rabbitMQConfig = options.Value;
}

2.2.2 映射项到模型类

            var info = new RabbitMQConfig();
            Configuration.Bind(RabbitMQConfig.RabbitMQ, info);
            //or
            Configuration.GetSection(RabbitMQConfig.RabbitMQ).Bind(info);

微信公众号

技术分享图片

.Net之配置文件

原文:https://www.cnblogs.com/ITzhangyunpeng/p/14729035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!